简体   繁体   English

在 Python Pandas MultiIndex 中重命名名称

[英]Rename name in Python Pandas MultiIndex

I try to rename a column name in a Pandas MultiIndex but it doesn't work.我尝试重命名 Pandas MultiIndex 中的列名称,但它不起作用。 Here you can see my series object.在这里你可以看到我的系列对象。 Btw, why is the dataframe df_injury_record becoming a series object in this function?顺便说一句,为什么数据帧 df_injury_record 成为这个函数中的一个系列对象?

Frequency_BodyPart = df_injury_record.groupby(["Surface","BodyPart"]).size()

In the next line you will see my try to rename the column.在下一行中,您将看到我尝试重命名该列。

Frequency_BodyPart.rename_axis(index={'Surface': 'Class'})

But after this, the column has still the same name.但在此之后,该列仍然具有相同的名称。

Regards问候

One possible problem should be pandas version under 0.24 or you forget assign back like mentioned @anky_91:一个可能的问题应该是0.24以下的 pandas 版本,或者你忘记像@anky_91 提到的那样分配回来:

df_injury_record = pd.DataFrame({'Surface':list('aaaabbbbddd'),
                                 'BodyPart':list('abbbbdaaadd')})

Frequency_BodyPart = df_injury_record.groupby(["Surface","BodyPart"]).size()
print (Frequency_BodyPart)
Surface  BodyPart
a        a           1
         b           3
b        a           2
         b           1
         d           1
d        a           1
         d           2
dtype: int64

Frequency_BodyPart = Frequency_BodyPart.rename_axis(index={'Surface': 'Class'})
print (Frequency_BodyPart)
Class  BodyPart
a      a           1
       b           3
b      a           2
       b           1
       d           1
d      a           1
       d           2
dtype: int64

If want 3 columns DataFrame working also for oldier pandas versions:如果想要 3 列 DataFrame 也适用于较旧的 pandas 版本:

df = Frequency_BodyPart.reset_index(name='count').rename(columns={'Surface': 'Class'})
print (df)
  Class BodyPart  count
0     a        a      1
1     a        b      3
2     b        a      2
3     b        b      1
4     b        d      1
5     d        a      1
6     d        d      2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM