获取类型错误:不可哈希类型:使用 loc 切片多级列时'slice'



目标是对0级a进行切片。

但是,当按如下方式对多索引列进行切片时,

a_cols=df.loc[:,('a',slice(None))]

编译器返回

TypeError: unhashable type: 'slice'
import pandas as pd
import numpy as np
np.random.seed(0)
arr=np.random.randint(5, size=(2, 12))
df=pd.DataFrame(arr,columns=[('a','E1_g1'),('a','E1_g2'),('a','E1_g3'),
('a','E2_g1'),('a','E2_g2'),('a','E2_g3'),
('a','E3_g1'),('a','E3_g2'),('a','E3_g3'),
('b','E1'),('b','E1'),('b','E13'),])

我可以知道我哪里做错了吗?

我也试过

df.loc[:, df.columns.get_level_values(0) == 'a']

但是,生成一个空的df

这是因为df.columns不是MultiIndex。您可以使用通过过滤df.columns创建的列表对其进行索引:

cols = [(i,j) for (i,j) in df.columns if i=='a']
out = df[cols]

输出:

(a, E1_g1)  (a, E1_g2)  (a, E1_g3)  (a, E2_g1)  (a, E2_g2)  (a, E2_g3)  (a, E3_g1)  (a, E3_g2)  (a, E3_g3)
0           4           0           3           3           3           1           3           2           4
1           2           1           0           1           1           0           1           4           3

您可以使用MultiIndex.from_tuples来创建df.columnsMultiIndex。然后你的切片方法工作:

df.columns = pd.MultiIndex.from_tuples(df.columns)
a_cols = df.loc[:,('a',slice(None))]

输出:

a                                                
E1_g1 E1_g2 E1_g3 E2_g1 E2_g2 E2_g3 E3_g1 E3_g2 E3_g3
0     4     0     3     3     3     1     3     2     4
1     2     1     0     1     1     0     1     4     3

最新更新