[英]python pandas dataframe rename a colume to a multiindex column
I have the following dataframe
我有以下dataframe
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.random((4,4)))
df
Out[5]:
0 1 2 3
0 0.136122 0.948477 0.173869 0.929373
1 0.194699 0.759875 0.723993 0.497966
2 0.323100 0.443267 0.210721 0.681426
3 0.590853 0.710664 0.202502 0.950658
I also have a column mapper:我还有一个列映射器:
mapping = {0: ('1', 'A'), 1: ('1', 'B'), 2: ('2', 'A'), 3: ('2', 'B')}
Is there a way to use mapping
to rename the column in df
to the below?有没有办法使用mapping
将df
的列重命名为以下内容? that is change the column to a multiindex by the mapping directly.即通过映射直接将列更改为多索引。
1 2
A B A B
0 0.136122 0.948477 0.173869 0.929373
1 0.194699 0.759875 0.723993 0.497966
2 0.323100 0.443267 0.210721 0.681426
3 0.590853 0.710664 0.202502 0.950658
ps, I know I can simply do the below, ps,我知道我可以简单地执行以下操作,
df.columns = pd.MultiIndex.from_product([['1','2'],['A','B']])
Use Index.map
, if use pandas 0.23+ is possible omit .get
:使用Index.map
,如果使用 pandas 0.23+ 是可能的省略.get
:
df.columns = df.columns.map(mapping.get)
print (df)
1 2
A B A B
0 0.696469 0.286139 0.226851 0.551315
1 0.719469 0.423106 0.980764 0.684830
2 0.480932 0.392118 0.343178 0.729050
3 0.438572 0.059678 0.398044 0.737995
Another solution with rename
, but is necessary convert to MultiIndex
in next step:另一个带有rename
解决方案,但在下一步中必须转换为MultiIndex
:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.