1

I have this Pandas series that contains lists of countries as following:

[United States of America]                                                     17851
[]                                                                              6288
[United Kingdom]                                                                2238
[France]                                                                        1654
[Japan]                                                                         1356
                                                                               ...  
[Canada, Switzerland, France]                                                      1
[Canada, Hungary, United Kingdom]                                                  1
[France, Germany, Italy, Romania, United Kingdom, United States of America]        1
[Germany, Russia, United Kingdom, United States of America]                        1
[Germany, Serbia]                                                                  1
Name: production_countries, Length: 2390, dtype: int64

I want to iterate over it and delete any element that has United States of America in it. I tried:

for row in df.production_countries:
    if 'United States of America' in row:
        df.drop(row)

But it gives me the following keyerror:

KeyError: "['United States of America'] not found in axis"
Fatimah E.
  • 101
  • 1
  • 5
  • 1
    Does this answer your question? [How to delete rows from a pandas DataFrame based on a conditional expression](https://stackoverflow.com/questions/13851535/how-to-delete-rows-from-a-pandas-dataframe-based-on-a-conditional-expression) – Mady Daby Apr 24 '21 at 22:02
  • No, because the iterable element in my case is a list. – Fatimah E. Apr 24 '21 at 22:04
  • In particular, you must reference the list, not the row as a whole. Write the condition based on that column. We can't fix your code, since you failed to post the expected see [MRE - Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). – Prune Apr 24 '21 at 22:04
  • This one liner should work : `df = df.drop(df["United States of America" in df.production_countries].index)` – Mady Daby Apr 24 '21 at 22:07

0 Answers0