Skip to main content
 首页 » 编程设计

python之根据外观过滤 Pandas 交叉表

2025年05月04日18hnrainll

我有一个巨大的 Pandas 交叉表,我想过滤只出现一次的项目,为了更容易解释,我会制作人工数据,这是我的数据

Customer_id        Apple     Book    Candy 
1                  0         1       1 
2                  1         1       0 
3                  1         1       0 
4                  1         0       0 

因为Candy只出现过一次,所以结果会是这样

Customer_id        Apple     Book  
1                  0         1       
2                  1         1        
3                  1         1        
4                  1         0        

请您参考如下方法:

使用 dropna

df.replace(0,np.nan).dropna(axis=1,thresh=2).fillna(0).astype(int) 
Out[18]:  
   Customer_id  Apple  Book 
0            1      0     1 
1            2      1     1 
2            3      1     1 
3            4      1     0