pandas :合并multiIndex DataFrame的标题行 [英] Pandas: combining header rows of a multiIndex DataFrame

查看:89
本文介绍了 pandas :合并multiIndex DataFrame的标题行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个如下的DataFrame:

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

,我想创建一个新的DataFrame,如下所示:

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

可能的代码是什么?

推荐答案

1.使用Python 3.6及更高版本进行更新,将 f字符串格式与列表一起使用理解力:

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.使用mapjoin:

2. Use map and join:

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

3.如果您的列具有数字数据类型,请使用mapformat:

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

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

输出:

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

这篇关于 pandas :合并multiIndex DataFrame的标题行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆