ritzrori
ritzrori

Reputation: 91

Converting dtype: period[M] to string format

I have converted my dates in to an Dtype M format as I don't want anything to do with the dates. Unfortunately I cannot plot with this format so I want now convert this in to strings.

So I need to group my data so I can print out some graphs by months. But I keep getting a serial JSON error when my data is in dtype:Mperiod so I want to convert it to strings.

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')

It returns a string of numbers, but I need it to return a string output.

Upvotes: 3

Views: 3508

Answers (1)

jezrael
jezrael

Reputation: 862751

Use Series.dt.strftime for set Series to strings in last step:

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

Or set it before groupby, then converting to month period is not necessary:

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

Upvotes: 1

Related Questions