pandas 0.20:带有多级索引列的 df - 如何过滤多列的条件?

时间:2021-07-27 04:00:14

标签: python pandas

我想找到所有 3 列都 >0 的所有行。我该怎么做?谢谢!我知道将 loc 与 IndexSlicer 一起使用可以返回一列 True/False。

但它不适用于多列的条件,或返回值表。

Importance| A         |  B   | C       |
Category | Cat1       | Cat2 | Cat1    |
         |Total Assets| AUMs | Revenue |
Firm 1   | 100        | 300  | 300     |
Firm 2   | 200        | 3400 | 200     |
Firm 3   | 300        | 800  | 400     |
Firm 4   | NaN        | 800  | 350     |

idx=pd.IndexSlice
df.sort_index(ascending=True, inplace=True, axis=1)
df.loc[:,idx[:,'Cat1','Total Assets']]>0

Importance| A         |  
Category | Cat1       | 
         |Total Assets| 
Firm 1   | T       | 
Firm 2   | T       | 
Firm 3   | T       |
Firm 4   | F       |

期望输出:

Importance| A         |  B   | C       |
Category | Cat1       | Cat2 | Cat1    |
         |Total Assets| AUMs | Revenue |
Firm 1   | 100        | 300  | 300     |
Firm 2   | 200        | 3400 | 200     |
Firm 3   | 300        | 800  | 400     |

1 个答案:

答案 0 :(得分:2)

IIUC:

InfoSaveFiles

更新

<块引用>

我只想要过滤 col 'TotalAssets'>0 & 'Revenue'>0?

>>> df[df.iloc[:, 1:].gt(0).all(axis=1)]

  Importance           A     B       C
    Category        Cat1  Cat2    Cat1
             TotalAssets  AUMs Revenue
0      Firm1       100.0   300     300
1      Firm2       200.0  3400     200
2      Firm3       300.0   800     400
相关问题