如何在pandas DataFrame中展平层次结构的列索引? [英] How do I flatten a hierarchical column index in a pandas DataFrame?

查看:181
本文介绍了如何在pandas DataFrame中展平层次结构的列索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个pandas.DataFrame,其列上的层次结构索引如下:

Say I have a pandas.DataFrame with a hierarchical index on the columns as follows:

import pandas as pd
columns = pd.MultiIndex.from_product([list('AB'), list('ab')])
df = pd.DataFrame(np.arange(8).reshape((2,4)), columns=columns)
print df

出[1]:

   A     B   
   a  b  a  b
0  0  1  2  3
1  4  5  6  7

我想使列索引变平,如下所示:

I would like to flatten the column index so it looks as follows:

   Aa  Ab  Ba  Bb
0   0   1   2   3
1   4   5   6   7

我尝试过

def flatten(col):
    col.name = ''.join(col.name)
    return col

df.apply(f)

但这只是忽略了新列的修改名称.

but that just ignored the modified name of the new columns.

推荐答案

set_axis

df.set_axis([f"{x}{y}" for x, y in df.columns], axis=1, inplace=False)

   Aa  Ab  Ba  Bb
0   0   1   2   3
1   4   5   6   7


index.map


index.map

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

   Aa  Ab  Ba  Bb
0   0   1   2   3
1   4   5   6   7


对于非字符串列值

df.columns = df.columns.map(lambda x: ''.join([*map(str, x)]))
df

   Aa  Ab  Ba  Bb
0   0   1   2   3
1   4   5   6   7

这篇关于如何在pandas DataFrame中展平层次结构的列索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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