Pandas: combining header rows of a multiIndex DataFrame

梦想与她 提交于 2020-01-10 00:05:47

问题


Lets say I have a DataFrame as follows:

first   bar       baz       foo
second  one  two  one  two  one  two three
A       1    2    3    4    5    6   7
B       8    9    10   11   12   13  14

and I want to create a new DataFrame like this:

        barone  bartwo  bazone baztwo  fooone footwo foothree
A       1       2       3      4       5      6      7
B       8       9       10     11      12     13     14

What would be the possible code?


回答1:


1. Update using Python 3.6+ use f-string formatting with list comprehension:

df.columns = [f'{i}{j}' for i, j in df.columns]

2. Use map and join:

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

3. If your columns has numeric datatypes, use map and format:

df.columns = df.columns.map('{0[0]}{0[1]}'.format) 

Output:

   barone  bartwo  bazone  baztwo  fooone  footwo  foothree
A       1       2       3       4       5       6         7
B       8       9      10      11      12      13        14


来源:https://stackoverflow.com/questions/47637153/pandas-combining-header-rows-of-a-multiindex-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!