Python 如何简单地将列级别添加到 Pandas 数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40225683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:18:56  来源:igfitidea点击:

How to simply add a column level to a pandas dataframe

pythonpandasdataframemulti-level

提问by Steven G

let say I have a dataframe that looks like this:

假设我有一个如下所示的数据框:

df = pd.DataFrame(index=list('abcde'), data={'A': range(5), 'B': range(5)})
 df
Out[92]: 
   A  B
a  0  0
b  1  1
c  2  2
d  3  3
e  4  4

Asumming that this dataframe already exist, how can I simply add a level 'C' to the column index so I get this:

假设这个数据框已经存在,我怎么能简单地向列索引添加一个级别“C”,所以我得到了这个:

 df
Out[92]: 
   A  B
   C  C
a  0  0
b  1  1
c  2  2
d  3  3
e  4  4

I saw SO anwser like this python/pandas: how to combine two dataframes into one with hierarchical column index?but this concat different dataframe instead of adding a column level to an already existing dataframe.

我看到了这样的答案python/pandas:如何将两个数据帧与分层列索引合并为一个?但是这个连接不同的数据帧而不是向已经存在的数据帧添加列级别。

-

——

回答by Romain

As suggested by @StevenG himself, a better answer:

正如@StevenG 本人所建议的,一个更好的答案:

df.columns = pd.MultiIndex.from_product([df.columns, ['C']])

print(df)
#    A  B
#    C  C
# a  0  0
# b  1  1
# c  2  2
# d  3  3
# e  4  4

回答by piRSquared

option 1
set_indexand T

选项 1
set_indexT

df.T.set_index(np.repeat('C', df.shape[1]), append=True).T

option 2
pd.concat, keys, and swaplevel

选项 2
pd.concat, keys, 和swaplevel

pd.concat([df], axis=1, keys=['C']).swaplevel(0, 1, 1)

enter image description here

在此处输入图片说明

回答by Anton Abrosimov

Another way for MultiIndex (appanding 'E'):

MultiIndex (appanding 'E') 的另一种方式:

df.columns = pd.MultiIndex.from_tuples(map(lambda x: (x[0], 'E', x[1]), df.columns))

   A  B
   E  E
   C  D
a  0  0
b  1  1
c  2  2
d  3  3
e  4  4