2016-12-28 48 views

回答

6

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

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