Skip to main content
 首页 » 编程设计

python之在 Pandas 中显示列

2024年10月17日8telwanggs

我在 pandas 中有一个术语 x 文档矩阵(由 CSV 制成),形式如下:

cheese, milk, bread, butter 
0,2,1,0 
1,1,0,0 
1,1,1,1 
0,1,0,1  

因此,如果我说“给我索引 1 和 2 处的列,其中给定行的值都大于 0”。

我想以此结束:

cheese, milk, 
[omitted] 
1,1 
1,1 
[omitted] 

这样,我可以对行数/文档数求和,得到一个频繁项集,即(cheese, milk) --[2/4 支持]

我已经按照单独的 stackoverflow 线程中的指示尝试了这种方法:

fil_df.select([fil_df.columns[1] > 0 and fil_df.columns[2] > 0], [fil_df.columns[1], fil_df.columns[2]]) 

但遗憾的是它对我不起作用。我收到错误:

TypeError: unorderable types: str() > int()

我不知道如何解决这个问题,因为当我从 csv 制作数据框时,我无法使行的单元格成为整数。

请您参考如下方法:

您可以使用 iloc与 boolean indexing :

#get 1. and 2. columns 
subset = df.iloc[:, [0,1]] 
print (subset) 
   cheese  milk 
0       0     2 
1       1     1 
2       1     1 
3       0     1 
 
#mask 
print ((subset > 0)) 
  cheese  milk 
0  False  True 
1   True  True 
2   True  True 
3  False  True 
 
#get all values where True by rows 
print ((subset > 0).all(1)) 
0    False 
1     True 
2     True 
3    False 
dtype: bool 
 
#get first and second columns names 
print (df.columns[[0,1]]) 
Index(['cheese', 'milk'], dtype='object') 
 
print (df.ix[(subset > 0).all(1), df.columns[[0,1]]]) 
   cheese  milk 
1       1     1 
2       1     1