格式化pandas列中的Quarter时间

时间:2016-12-28 20:26:44

标签: python pandas datetime format date-formatting

我的DataFrame列中包含DateTime索引,代表以下几个部分:

2000-03-31 00:00:00

如何将其转换为' 2000q1'?

我查看了文档,但他们只说DateTimeIndex.quarter 这里:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.quarter.html

format='%Y%q'不起作用。选项on='%Y%q

也不是。Promises

1 个答案:

答案 0 :(得分:12)

您可以使用xml_text = """<?xml version="1.0" encoding="UTF-8"?> <slave> <name>test.server</name> <description></description> <remoteFS>/var/lib/jenkins</remoteFS> <numExecutors>1</numExecutors> <mode>EXCLUSIVE</mode> <retentionStrategy class="hudson.slaves.RetentionStrategy$Always"/> <launcher class="hudson.plugins.sshslaves.SSHLauncher" plugin="ssh-slaves@1.10"> <host>test.server</host> <port>7777</port> <credentialsId>d0970a8f-d124</credentialsId> <maxNumRetries>0</maxNumRetries> <retryWaitTime>0</retryWaitTime> </launcher> <label>BuildServer</label> <nodeProperties/> <userId>test</userId> </slave> """ import xml.etree.ElementTree root = xml.etree.ElementTree.fromstring(xml_text) # show only a particular tag for name in root.findall('name'): print(name.text) # show all children at first level for child in root: print('%s: %s' % (child.tag, child.text)) # build a dict (will only get last of any duplicate tags, and no children) slave = {child.tag: child.text for child in root} # build a dict (will only get last of any duplicate tags) def xml_todict(xml_node): dict_ = {} for child in xml_node: dict_[child.tag] = xml_todict(child) dict_.update(xml_node.attrib) if not dict_: return xml_node.text if xml_node.text and 'text' not in dict_: dict_['text'] = xml_node.text return dict_ slave = xml_todict(root)

to_period("Q")
df.index = df.index.to_period("Q")

要转换普通列import pandas as pd df = pd.DataFrame({"y": [1,2,3]}, index=pd.to_datetime(["2000-03-31 00:00:00", "2000-05-31 00:00:00", "2000-08-31 00:00:00"])) df.index = df.index.to_period("Q") df # y #2000Q1 1 #2000Q2 2 #2000Q3 3 ,请使用col访问该系列中的dt个对象:

Datetime