簡體   English   中英

根據涉及多個列的復雜條件刪除行

[英]Dropping rows based on complex conditions involving multiple columns

aps1_risk.head()
Out[33]: 
   ID  class     S3   S22  S23   S26_3  S28  S29            
0   1      1  45698  1012  268  287230    0   10           
1   2      0      0     0    0  154298   86  454           
2   3      0    228   358  110  254892  128  202           

在這個給定的數據集中,我需要刪除class = 1且所有其他變量= 0的所有行。我想到了使用if else條件,但是有沒有更簡單的選擇? 任何幫助將不勝感激。 謝謝。

使用boolean indexing

df = aps1_risk[aps1_risk.drop('class', 1).ne(0).all(1) | aps1_risk['class'].ne(1)]

通過~反轉最終掩模的替代解決方案:

df = df[~(df.drop('class', 1).eq(0).any(1) & df['class'].eq(1))]

print (df)
   ID  class   S3  S22  S23   S26_3  S28  S29
1   2      0    0    0    0  154298   86  454
2   3      0  228  358  110  254892  128  202

詳細說明

比較所有列無class ,如果不等於0通過行的每個值all

print (df.drop('class', 1).ne(0).all(1))
0    False
1    False
2     True
dtype: bool

如果不等於1則比較列:

print (df['class'].ne(1))
0    False
1     True
2     True
Name: class, dtype: bool

和鏈條條件在一起:

print (df.drop('class', 1).ne(0).all(1) | df['class'].ne(1))
0    False
1     True
2     True
dtype: bool

因此它過濾True

df = aps1_risk[aps1_risk.drop('class', 1).ne(0).all(1) | aps1_risk['class'].ne(1)]
print (df)
   ID  class   S3  S22  S23   S26_3  S28  S29
1   2      0    0    0    0  154298   86  454
2   3      0  228  358  110  254892  128  202

Pandas允許您使用非常簡單的選擇語法,如下所示:

aps1_risk = aps1_risk[aps1_risk['class'] != 1]

或者您可以像這樣轟炸更復雜的查詢:

aps1_risk = aps1_risk[(aps1_risk['class'] != 1) | (aps1_risk.drop('class', 1) == 0)] 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM