仅在一列中重命名 multiindex headers
Rename multiindex headers in one column only
我正在尝试更改多索引数据帧的子列 headers。诀窍是我只是想更改其中一个超列下的 header。见下文
给定:
df = pd.DataFrame([[1,2,3,4], [10,20,30,40], [100,200,300,400]])
df.columns = pd.MultiIndex.from_tuples((("a", "b"), ("a", "c"), ("d", "b"), ("d", "c")))
我想将 header b
列更改为 j
但仅在 a
列下;我希望 d
列下的 header 保持不变。
如果我想要更改所有列 b
,我将执行以下操作
df.rename(columns={'b': 'j'}, level=1)
如何指定要更改子栏标题的超级栏?
我觉得这样可以吗?
import pandas as pd
df = pd.DataFrame([[1,2,3,4], [10,20,30,40], [100,200,300,400]])
df.columns = pd.MultiIndex.from_tuples((("a", "b"), ("a", "c"), ("d", "b"), ("d", "c")))
print(df)
a d
b c b c
0 1 2 3 4
1 10 20 30 40
2 100 200 300 400
现在重命名列:
df.columns = pd.MultiIndex.from_tuples((("a", "j"), ("a", "c"), ("d", "b"), ("d", "c")))
print(df)
a d
j c b c
0 1 2 3 4
1 10 20 30 40
2 100 200 300 400
你可以试试这个:(不太好但有效)
df.columns = pd.MultiIndex.from_tuples([(x,'j') if (x=='a' and y=='b') else (x,y) for x,y in df.columns])
您可以 map
遍历列名并检查索引是否为 ('a', 'b')
,如果匹配,则将 b
替换为 j
:
df.columns = df.columns.map(lambda x: ('a', 'j') if x == ('a', 'b') else x)
df
# a d
# j c b c
#0 1 2 3 4
#1 10 20 30 40
#2 100 200 300 400
我正在尝试更改多索引数据帧的子列 headers。诀窍是我只是想更改其中一个超列下的 header。见下文
给定:
df = pd.DataFrame([[1,2,3,4], [10,20,30,40], [100,200,300,400]])
df.columns = pd.MultiIndex.from_tuples((("a", "b"), ("a", "c"), ("d", "b"), ("d", "c")))
我想将 header b
列更改为 j
但仅在 a
列下;我希望 d
列下的 header 保持不变。
如果我想要更改所有列 b
,我将执行以下操作
df.rename(columns={'b': 'j'}, level=1)
如何指定要更改子栏标题的超级栏?
我觉得这样可以吗?
import pandas as pd
df = pd.DataFrame([[1,2,3,4], [10,20,30,40], [100,200,300,400]])
df.columns = pd.MultiIndex.from_tuples((("a", "b"), ("a", "c"), ("d", "b"), ("d", "c")))
print(df)
a d
b c b c
0 1 2 3 4
1 10 20 30 40
2 100 200 300 400
现在重命名列:
df.columns = pd.MultiIndex.from_tuples((("a", "j"), ("a", "c"), ("d", "b"), ("d", "c")))
print(df)
a d
j c b c
0 1 2 3 4
1 10 20 30 40
2 100 200 300 400
你可以试试这个:(不太好但有效)
df.columns = pd.MultiIndex.from_tuples([(x,'j') if (x=='a' and y=='b') else (x,y) for x,y in df.columns])
您可以 map
遍历列名并检查索引是否为 ('a', 'b')
,如果匹配,则将 b
替换为 j
:
df.columns = df.columns.map(lambda x: ('a', 'j') if x == ('a', 'b') else x)
df
# a d
# j c b c
#0 1 2 3 4
#1 10 20 30 40
#2 100 200 300 400