gpt4 book ai didi

python - Pandas - 在重命名期间创建多索引列

转载 作者:行者123 更新时间:2023-12-01 01:43:51 25 4
gpt4 key购买 nike

我正在尝试找到一种简单的方法将平面列索引重命名为分层多索引列集。我遇到过一种方法,但似乎有点笨拙 - 在 Pandas 中是否有更好的方法来做到这一点?

#!/usr/bin/env python
import pandas as pd
import numpy as np

flat_df = pd.DataFrame(np.random.randint(0,100,size=(4, 4)), columns=list('ACBD'))

print flat_df

# A C B D
# 0 27 67 35 36
# 1 80 42 93 20
# 2 64 9 18 83
# 3 85 69 60 84


nested_columns = {'A': ('One', 'a'),
'C': ('One', 'c'),
'B': ('Two', 'b'),
'D': ('Two', 'd'),
}

tuples = sorted(nested_columns.values(), key=lambda x: x[1]) # Sort by second value
nested_df = flat_df.sort_index(axis=1) # Sort dataframe by column name
nested_df.columns = pd.MultiIndex.from_tuples(tuples)
nested_df = nested_df.sort_index(level=0, axis=1) # Sort to group first level

print nested_df

# One Two
# a c b d
# 0 27 67 35 36
# 1 80 42 93 20
# 2 64 9 18 83
# 3 85 69 60 84

对分层列规范和数据框进行排序并假设它们会对齐似乎有点脆弱。而且排序三遍似乎很荒谬。我更喜欢的替代方案是类似于 nested_df = flat_df.rename(columns=nested_columns) ,但似乎 rename 无法从平面列索引中进行到多索引列。我错过了什么吗?

编辑:意识到如果按第二个值排序的元组与平面列名称的排序方式不同,这会中断。 绝对是错误的方法。

编辑2:回应@wen的回答:

nested_df = flat_df.rename(columns=nested_columns)
print nested_df
# (One, a) (One, c) (Two, b) (Two, d)
# 0 18 0 51 48
# 1 69 68 78 24
# 2 2 20 99 46
# 3 1 80 11 11

编辑3:

根据 @ScottBoston 的回答,这是一个可行的解决方案,可以解决嵌套列中未提及的平面列:

#!/usr/bin/env python
import pandas as pd
import numpy as np

flat_df = pd.DataFrame(np.random.randint(0,100,size=(4, 5)), columns=list('ACBDE'))

print flat_df
# A C B D E
# 0 27 68 4 98 16
# 1 0 9 9 72 68
# 2 91 17 19 54 99
# 3 14 96 54 79 28

nested_columns = {'A': ('One', 'e'),
'C': ('One', 'h'),
'B': ('Two', 'f'),
'D': ('Two', 'g'),
}

nested_df = flat_df.rename(columns=nested_columns)
nested_df.columns = [c if isinstance(c, tuple) else ('', c) for c in nested_df.columns]
nested_df.columns = pd.MultiIndex.from_tuples(nested_df.columns)

print nested_df
# One Two
# e h f g E
# 0 27 68 4 98 16
# 1 0 9 9 72 68
# 2 91 17 19 54 99
# 3 14 96 54 79 28

最佳答案

你可以尝试:

df.columns = pd.MultiIndex.from_tuples(df.rename(columns = nested_columns).columns)
df

输出:

  One     Two    
a c b d
0 27 67 35 36
1 80 42 93 20
2 64 9 18 83
3 85 69 60 84

关于python - Pandas - 在重命名期间创建多索引列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51604679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com