Pandas 灵活的布尔行子设置

Pandas flexible boolean row sub setting

是否可以通过单个值的多个行条件对 Pandas 1.3.4 数据框进行子集化?为了使这一点更清楚,如果我有 df:

index    col1    col2    
  0        A      10
  1        A      20
  2        B      130
  3        C      10

如果我想根据 col2 值进行子集化,我可以 df[df['col2']>10]:

index    col1    col2    
  
  1        A      20
  2        B      130

  

但是是否可以根据 col1 值使用不同的阈值对 col2 进行子集化?

例如:

df[df['col2']>10 if col1 == 'A' 
   OR df['col2']>5 if col1 == 'C' 
   OR df['col2']>1000 if col1 == 'B']` 

会给出:

index    col1    col2    
  
  1        A      20
  
  3        C      10

谢谢!

蒂姆

如果需要比较更大的所有值,请按字典使用 Series.map 并比较:

d = {'A' : 10,'C': 5 ,'B': 1000}

df[df['col2'] > df['col1'].map(d)]

或者如果需要不同的掩码链,按位 & AND| 按位 OR:

df[((df['col2']>10) & (df['col1']== 'A') ) |
   ((df['col2']>5) & (df['col1']== 'C') ) |
   ((df['col2']>1000) & (df['col1']== 'B') )]