python - Renaming column in pandas with a multi level index
问题描述
I would like to rename 'multi level columns' of a pandas dataframe to 'single level columns'. My code so far does not give any errors but does not rename either. Any suggestions for code improvements?
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
I prefer to use the rename
method. df.columns = ['Country', 'GDP']
works but is not what I am looking for.
解决方案
For rename
solution create dictionary by flatten values of MultiIndex
with join
with new columns names in 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)))
If want create dictionary for rename:
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
推荐阅读
- python - 使用python将HTML表格转换为CSV文件
- javascript - 在数组中使用 forEach 查找对象并在 TypeScript 中更改它的值
- android - 未设置 Android OpenGL 渲染器 - 无错误
- c# - Azure Function HTTP 在一次执行中多次执行
- python - 在 ElasticSearch 中,如何检查字段是否存在则应仅返回布尔值( True 或 False )
- mongodb - Mongodb按一列多值排序
- asp.net - Microsoft.NET.Sdk.Web 缺少 Web 菜单 (ASP.NET)
- doxygen - 如何在 doxygen 配置文件(例如 iostream 库)中添加不带扩展名的文件?
- angular - Angular:HTTP调用完成之前的函数返回值
- mongodb - 使用游标聚合 Mongodb 集合