pandas 在熊猫列中格式化季度时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41369227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:41:05  来源:igfitidea点击:

Formatting Quarter time in pandas columns

pythonpandasdatetimeformatdate-formatting

提问by B Furtado

I have a DataFramewith columns in DateTimeindex, representing quarters such as:

DataFrameDateTime索引中有一个列,代表季度,例如:

2000-03-31 00:00:00

How can I do to transform this into '2000q1'?

我该怎么做才能将其转换为“2000q1”?

I have looked around the docs, but they only say DateTimeIndex.quarter Here: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.quarter.html

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

format='%Y%q'does not work. Neither does the option on='%Y%q

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

回答by Psidom

You can use to_period("Q"):

您可以使用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


To convert a normal column col, use dtto access the Datetimeobjects in the series:

要转换普通列col,请使用dt访问Datetime系列中的对象:

df = pd.DataFrame({"y": [1,2,3], 'col': pd.to_datetime(["2000-03-31 00:00:00", "2000-05-31 00:00:00", "2000-08-31 00:00:00"])})


df['col'] = df['col'].dt.to_period("Q")

df
#      col  y
#0  2000Q1  1
#1  2000Q2  2
#2  2000Q3  3