1 回答

TA贡献1862条经验 获得超6个赞
您可以使用列名创建元组,然后将匹配字典与第二个参数一起用作get默认值,因此如果不匹配则不替换:
L = [(a, reps[a].get(b, b)) if a in reps else (a, b) for a, b in df.columns.tolist()]
df.columns = pd.MultiIndex.from_tuples(L)
print (df)
col_0 col_1 col_2
o one two o2 one2 two2 o3 one3 two3
1 2 2 2 2 2 2 2 2 2
3 4 4 4 4 4 4 4 4 4
测试字典中是否没有匹配的外键reps:
reps = {
"col_100": {0: "o", 1: "one", 2: "two"},
"col_1": {0: "o2", 1: "one2", 2: "two2"},
"col_2": {0: "o3", 1: "one3", 2: "two3"},
}
L = [(a, reps[a].get(b, b)) if a in reps else (a, b) for a, b in df.columns.tolist()]
df.columns = pd.MultiIndex.from_tuples(L)
print (df)
col_0 col_1 col_2
0 1 2 o2 one2 two2 o3 one3 two3
1 2 2 2 2 2 2 2 2 2
3 4 4 4 4 4 4 4 4 4
测试是否没有匹配的内部键:
reps = {
"col_0": {100: "o", 1: "one", 20: "two"},
"col_1": {0: "o2", 1: "one2", 2: "two2"},
"col_2": {0: "o3", 1: "one3", 2: "two3"},
}
L = [(a, reps[a].get(b, b)) if a in reps else (a, b) for a, b in df.columns.tolist()]
df.columns = pd.MultiIndex.from_tuples(L)
print (df)
col_0 col_1 col_2
0 one 2 o2 one2 two2 o3 one3 two3
1 2 2 2 2 2 2 2 2 2
3 4 4 4 4 4 4 4 4 4
添加回答
举报