pandas 检查三列条件并根据条件删除

ljo96ir5  于 2023-02-02  发布在  其他
关注(0)|答案(5)|浏览(183)

我在Pandas中有以下 Dataframe df

item    purchase_date   purchase_qty    purchase_price  other_adjustments     sold
0   0040030     2022-01     0   0.00             0                0.0
1   0050064     2022-01     0   0.00            -5                854.0
2   0050066     2022-01     0   0.00            2979                  0.0
3   0050202     2022-01     0   0.00            14673                 1320.0
4   0050204     2022-01     0   0.00            2538                  0.0

如果purchase_qty、other_adjustments和sold都为0,我需要删除行。
我试过这个

test_df = df[(df['purchase_qty'] != 0) & (df['other_adjustments'] != 0) & (df['sold'] != 0)]

此代码删除所有purchase_qty,它的值是0,但我想要的是检查这3列,如果所有三个都是0,然后删除。请帮助我

hjzp0vay

hjzp0vay1#

您需要使用or条件

test_df = df[(df['purchase_qty'] != 0) | (df['other_adjustments'] != 0) | (df['sold'] != 0)]

或者你可以做一个逆运算

test_df = df[~((df['purchase_qty'] == 0) & (df['other_adjustments'] == 0) & (df['sold'] == 0))]
k10s72fa

k10s72fa2#

如果至少有一个值不是0,则可以过滤3列-因此删除3列中所有0的行:

test_df = df[df[['purchase_qty','other_adjustments','sold']].ne(0).any(axis=1)] 
print (test_df)
    item purchase_date  purchase_qty  purchase_price  other_adjustments  \
1  50064       2022-01             0             0.0                 -5   
2  50066       2022-01             0             0.0               2979   
3  50202       2022-01             0             0.0              14673   
4  50204       2022-01             0             0.0               2538   

     sold  
1   854.0  
2     0.0  
3  1320.0  
4     0.0
mbzjlibv

mbzjlibv3#

你可以试试这个:
test_df = df[(df['purchase_qty'] != 0) | (df['other_adjustments'] != 0) | (df['sold'] != 0)]
此状态:如果这些值中有一个不为0,则保留它,否则过滤掉。

bnl4lu3b

bnl4lu3b4#

这个也行!!

df = df[(df[['purchase_qty', 'other_adjustments', 'sold']] != 0).any(axis=1)]
0yycz8jy

0yycz8jy5#

这是对所用方法的修复:
df = df.drop(df[(df.purchase_qty == 0) & (df.other_adjustments == 0) & (df.sold == 0.0)].index)

相关问题