熊猫-重命名期间创建Multiindex列

尼克·斯威特

我正在尝试找到一种简单的方法来将平列索引重命名为分层的multindex列集。我碰到了一种方法,但似乎有点糊涂-在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无法从平列索引转换为多索引列。我想念什么吗?

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

Edit2:回应@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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章