0

I am new to Pandas and I am trying to drop all rows that contain some respective countries (Albania, Uzbekistan, Brazil) from the Column country. However, the way I figured it out to do is one by one, as below:

indexCountry = df[df['country'] == 'Albania'].index
df.drop(indexCountry, inplace = True)

indexCountry = df[df['country'] == 'Uzbekistan'].index
df.drop(indexCountry, inplace = True)

indexCountry = df[df['country'] == 'Brazil'].index
df.drop(indexCountry, inplace = True)

Is there a way to do this in one single code line, instead of having to do one for every country?

3 Answers 3

1

You can do a filter like this:

df = df[~df["country"].isin(["Alabania", "Uzbekistan", "Brazil"])]

~ is the negation of what it is followed by.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thank you very much @Yilun Zhang
0

Try:

list_of_countries = ['Albania',  'Uzbekistan', 'Brazil']
indexCountry = df[df['country'].isin(list_of_countries)].index 
df.drop(indexCountry, inplace = True)

or just:
list_of_countries = ['Albania',  'Uzbekistan', 'Brazil']
df[~df["country"].isin(list_of_countries)]

Comments

0

You can also use this:

df = df[~df.country.str.contains('|'.join(["Albania","Uzbekistan","Brazil"]))]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.