使用多级索引重命名熊猫中的列

时间:2021-01-08 13:02:37

标签: python pandas indexing

我想将 Pandas 数据框的“多级列”重命名为“单级列”。到目前为止,我的代码没有给出任何错误,但也没有重命名。对代码改进有什么建议吗?

import pandas as pd

url = 'https://en.wikipedia.org/wiki/Gross_national_income'

df = pd.read_html(url)[3][[('Country', 'Country'), ('GDP[10]', 'GDP[10]')]]\
.rename(columns={('Country', 'Country'):'Country', ('GDP[10]', 'GDP[10]'): 'GDP'})

df  

我更喜欢使用 rename 方法。 df.columns = ['Country', 'GDP'] 有效,但不是我想要的。

2 个答案:

答案 0 :(得分:2)

对于 rename 解决方案,通过在 MultiIndex 中使用新列名称将 join 的值展平并使用 zip 创建字典:

url = 'https://en.wikipedia.org/wiki/Gross_national_income'
df = pd.read_html(url)[3]

df.columns = df.columns.map('_'.join)

old = ['No._No.', 'Country_Country', 'GNI (Atlas method)[8]_value (a)',
       'GNI (Atlas method)[8]_a - GDP', 'GNI[9]_value (b)', 'GNI[9]_b - GDP',
       'GDP[10]_GDP[10]']
new = ['No.','Country','GNI a','GDP a','GNI b', 'GNI b', 'GDP']

df = df.rename(columns=dict(zip(old, new)))

如果要创建重命名字典:

d = {'No._No.': 'No.', 'Country_Country': 'Country', 'GNI (Atlas method)[8]_value (a)': 'GNI a', 'GNI (Atlas method)[8]_a - GDP': 'GDP a', 'GNI[9]_value (b)': 'GNI b', 'GNI[9]_b - GDP': 'GNI b', 'GDP[10]_GDP[10]': 'GDP'}
df = df.rename(columns=d)

print (df)
   No.         Country     GNI a   GDP a     GNI b   GNI b       GDP
0    1   United States  20636317   91974  20837347  293004  20544343
1    2           China  13181372 -426779  13556853  -51298  13608151
2    3           Japan   5226599  255276   5155423  184100   4971323
3    4         Germany   3905321  -42299   4058030  110410   3947620
4    5  United Kingdom   2777405  -77891   2816805  -38491   2855296
5    6          France   2752034  -25501   2840071   62536   2777535
6    7           India   2727893    9161   2691040  -27692   2718732
7    8           Italy   2038376  -45488   2106525   22661   2083864
8    9          Brazil   1902286   16804   1832170  -53312   1885482
9   10          Canada   1665565  -47776   1694054  -19287   1713341

答案 1 :(得分:1)

对于“重命名”的替代方案,您可以使用 get_level_values()。见下文:

df.columns = df.columns.get_level_values(0)

>>> print(df)
          Country   GDP[10]
0   United States  20544343
1           China  13608151
2           Japan   4971323
3         Germany   3947620
4  United Kingdom   2855296
5          France   2777535
6           India   2718732
7           Italy   2083864
8          Brazil   1885482
9          Canada   1713341