将dtype:period [M]转换为字符串格式

时间:2019-07-24 11:32:17

标签: python pandas numpy

我已将日期转换为Dtype M格式,因为我不希望与日期有任何关系。不幸的是,我无法使用这种格式进行绘制,因此现在我想将其转换为字符串。

因此,我需要对数据进行分组,以便可以按月打印出一些图表。 但是,当我的数据位于dtype:Mperiod中时,我一直收到串行JSON错误 所以我想将其转换为字符串。

df['Date_Modified'] = pd.to_datetime(df['Collection_End_Date']).dt.to_period('M')  
#Add a new column called Date Modified to show just month and year

df = df.groupby(["Date_Modified", "Entity"]).sum().reset_index()
#Group the data frame by the new column and then Company and sum the values

df["Date_Modified"].index = df["Date_Modified"].index.strftime('%Y-%m')

它返回一个数字字符串,但是我需要它来返回字符串输出。

1 个答案:

答案 0 :(得分:0)

在最后一步中,使用Series.dt.strftimeSeries设置为字符串:

df["Date_Modified"]= df["Date_Modified"].dt.strftime('%Y-%m')

或将其设置为groupby之前,则不必转换为月周期:

df['Date_Modified'] = pd.to_datetime(df['Collection_End_Date']).dt.strftime('%Y-%m')
df = df.groupby(["Date_Modified", "Entity"]).sum().reset_index()