简体   繁体   中英

Python pandas: removing rows not matching multiple conditions from dataframe

Suppose I have a column using pandas.dataframe like so:

index  fruits    origin      attribute
 1     apple     USA         tasty
 2     apple     France      yummy
 3     apple     USA         juicy
 4     apple     England     juicy
 5     apple     Japan       normal
 6     banana    Canada      nice
 7     banana    Italy       good
 .....

I want to select yummy apple from France(2) and remove unmatching apples from table like the following:

index  fruits    origin      attribute
 1     apple     France      yummy
 2     banana    Canada      nice
 3     banana    Italy       good
 .....

I thought the following should work. But it doesn't:

df.drop(df[(df.fruits == "apple") & (df.origin != "France") | (df.fruits == "apple") & (df.attribute != "yummy")].index)

Then I tried the following which also doesn't work:

df = df[~df[(df.fruits == "apple") & (df.origin != "France") & (df.attribute != "yummy")]

Any help, lads?

If select by matching condition:

df[(df.fruits != 'apple') | ((df.fruits == 'apple') & (df.origin == 'France') & (df.attribute == 'yummy'))]

#index  fruits  origin  attribute
#1  2    apple  France      yummy
#5  6   banana  Canada       nice
#6  7   banana   Italy       good

If remove by non-matching condition: what needs to be removed are rows where fruits is apple but origin doesn't match France or attribute doesn't match yummy :

df[~((df.fruits == 'apple') & ((df.origin != 'France') | (df.attribute != 'yummy')))]

# index fruits  origin  attribute
#1    2  apple  France      yummy
#5    6 banana  Canada       nice
#6    7 banana   Italy       good
df.query(
    'fruits == "apple" & origin == "France" & attribute == "yummy"'
).append(df.query('fruits != "apple"'))

       fruits  origin attribute
index                          
2       apple  France     yummy
6      banana  Canada      nice
7      banana   Italy      good

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