选择pandas数据框中的列,并使用multiindex将它们分组

问题描述 投票:1回答:1

我有一个包含126列的巨大数据框。我想添加一个额外的级别(multiindex),我想拥有5个类别,因此126列中的每一个都将属于相应的类别。我发现了许多解决方案,它们定义了级别并写下了要添加到该级别的所有列,这确实很耗时,因为我必须将126列分组。有更快的方法吗?例如,使用.iloc[:,9:44]之类的列进行切片,因为我要将这35列分组为一个类别?

Dataframe看起来像这样:

    df
        a    b     c...  d    e     f...  g    h    i...  j    k    l... n=126

 1     1.0  1.0   1.0   2.0   3.0   2.0   1.0  1.0  1.0  2.0   3.0   2.0 
 2     4.0  5.0   4.0   4.0   8.0   4.0   4.0  5.0  4.0  4.0   8.0   4.0
 3     6.0  1.0   6.0   7.0   8.0   7.0   6.0  1.0  6.0  7.0   8.0   7.0

解决方案如下所示:

    df2
              A          |        B         |       C          |       D    n=5
        a    b     c...  |  d     e    f... |  g    h     i... |   j   k  l n=126 

1      1.0  1.0   1.0    2.0  3.0   2.0    1.0  1.0   1.0    2.0  3.0   2.0
2      4.0  5.0   4.0    4.0  8.0   4.0    4.0  5.0   4.0    4.0  8.0   4.0
3      6.0  1.0   6.0    7.0  8.0   7.0    6.0  1.0   6.0    7.0  8.0   7.0
pandas dataframe slice multi-index
1个回答
1
投票

如果要为每个N个块分配N个值以单独的类别创建字典,然后为map

#https://stackoverflow.com/a/312464/2901002
def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i:i + n]

L = ['A','B','C','D']
d = {v: k for k, x in zip(L, chunks(df.columns, 3)) for v in x}
print (d)
{'a': 'A', 'b': 'A', 'c': 'A', 
 'd': 'B', 'e': 'B', 'f': 'B', 
 'g': 'C', 'h': 'C', 'i': 'C', 
 'j': 'D', 'k': 'D', 'l': 'D'}

df.columns = [df.columns.map(d), df.columns]
print (df)

     A              B              C              D          
     a    b    c    d    e    f    g    h    i    j    k    l
1  1.0  1.0  1.0  2.0  3.0  2.0  1.0  1.0  1.0  2.0  3.0  2.0
2  4.0  5.0  4.0  4.0  8.0  4.0  4.0  5.0  4.0  4.0  8.0  4.0
3  6.0  1.0  6.0  7.0  8.0  7.0  6.0  1.0  6.0  7.0  8.0  7.0

编辑:如果需要按位置设置列:

d1 = {'A':df.columns[0:3],
      'B':df.columns[3:6],
      'C':df.columns[6:9],
      'D':df.columns[9:12]}
print (d1)
{'A': Index(['a', 'b', 'c'], dtype='object'), 
 'B': Index(['d', 'e', 'f'], dtype='object'), 
 'C': Index(['g', 'h', 'i'], dtype='object'), 
 'D': Index(['j', 'k', 'l'], dtype='object')}

d =  {v: k for k, x in d1.items() for v in x}
print (d)
{'a': 'A', 'b': 'A', 'c': 'A', 
 'd': 'B', 'e': 'B', 'f': 'B', 
 'g': 'C', 'h': 'C', 'i': 'C', 
 'j': 'D', 'k': 'D', 'l': 'D'}

df.columns = [df.columns.map(d), df.columns]
print (df)
     A              B              C              D          
     a    b    c    d    e    f    g    h    i    j    k    l
1  1.0  1.0  1.0  2.0  3.0  2.0  1.0  1.0  1.0  2.0  3.0  2.0
2  4.0  5.0  4.0  4.0  8.0  4.0  4.0  5.0  4.0  4.0  8.0  4.0
3  6.0  1.0  6.0  7.0  8.0  7.0  6.0  1.0  6.0  7.0  8.0  7.0
© www.soinside.com 2019 - 2024. All rights reserved.