How to delete rows from a data frame based on multiple conditions

Viewed 41

I have a DF named "faves", with a column named "fruit". In the column, there are four possible choices: apple, orange, grape, and strawberry. I am trying to drop all of the rows from the fruit column that isn't an apple or an orange. The code I got so far is :

X = faves[ (faves['fruit'] != "apple") & (faves['fruit'] != "orange") ].index

faves = faves.drop(faves[faves['fruit'] == X])

whenever I try it I get KeyError: 'fruit'

1 Answers

You made the drop statement very complex.

The below statement returns list of keys for the given condition

X = faves[ (faves['fruit'] != "apple") & (faves['fruit'] != "orange") ].index

Simply use it to drop.

faves = faves.drop(X)

output

    fruit
0   apple
1  orange

Complete Example

# INPUT DATA
d = {'fruit': ["apple","grape","strawberry","orange","cranberry"]}
faves = pd.DataFrame(data=d)

#        fruit
# 0       apple
# 1       grape
# 2  strawberry
# 3      orange
# 4   cranberry

#CONDITION
X = faves[ (faves['fruit'] != "apple") & (faves['fruit'] != "orange") ].index

# X will be the rows -- [1 (grape), 2 (strawberry) , 4 (cranberry]

#SIMPLY DROP X
faves = faves.drop(X)

print(faves)
Related