简体   繁体   中英

python, pandas, drop rows by condition

hello I need help to drop some rows by the condition: if the estimated price minus price is more than 1500 (positive) drop the row

    price      estimated price 
 0  13295                13795
 1  19990                22275
 2   7295                 6498

for example only the index 1 would be drop thank you!

You can use pd.drop() in which you can drop specific rows by index. :

>>> df.drop(df[(df['estimated price']-df['price'] >= 1500)].index)

   price  estimated price
0  13295            13795
2   7295             6498

index 1 is dropped.

Note that this method assumes that your index is unique. If otherwise, boolean indexing is the better solution.

Change logic for get all rows if less or equal like 1500 after subtracting in boolean indexing with Series.le :

df1 = df[df['estimated price'].sub(df['price']).le(1500)]

working like invert mask for greater like 1500 :

df1 = df[~df['estimated price'].sub(df['price']).gt(1500)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM