将数据类型从period[M]转换为字符串格式

3

我已经将我的日期转换为 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个回答

1

使用 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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接