For the past few hours, I've been trying to change/rename the name of my multiindex in my pandas Series but I do not know how to achieve it. I've been looking all kind of different things and I cannot seem to get it right. This is important because I have realized that if I do not do so, my two indexes have the same name (which is "date"). Here is the code:
df_bar = df.groupby([pd.Grouper(freq = "Y"), pd.Grouper(freq = "M")])["value"].mean()
if you print df_bar, you would have the following: print of df_bar
Would it be possible to name each index directly in the groupby()?
Thank you in advance for the help :)
CodePudding user response:
I think not, need rename in next step by Series.rename_axis
:
df = pd.DataFrame(
{
"date": [
pd.Timestamp("2000-01-02"),
pd.Timestamp("2000-01-02"),
pd.Timestamp("2001-01-09"),
pd.Timestamp("2001-01-16")
],
"value": [10, 20, 30, 40]
}
).set_index('date')
df_bar = (df.groupby([pd.Grouper(freq = "Y"), pd.Grouper(freq = "M")])["value"]
.mean()
.rename_axis(['Y','M']))
print (df_bar)
Y M
2000-12-31 2000-01-31 15
2001-12-31 2001-01-31 35
Name: value, dtype: int64