Is there a way to check if a list item is the ONLY item in the list?

Viewed 47

I have a list of dictionaries, the whole list represents different countries, and each dictionary includes basic data about each country as following: example a

df.countries[3]
"[{'iso_3166_1': 'DE', 'name': 'Germany'}, {'iso_3166_1': 'US', 'name': 'United States of America'}, {'iso_3166_1': 'IN', 'name': 'India'}]"

Of course, there are other cells where countries list has only one dictionary like this: example b

df.countries[0]
"[{'iso_3166_1': 'US', 'name': 'United States of America'}]"

Or empty list like this: example c

df.countries[505]
'[]'

What I want to do is:

  • Delete rows where country name is United States of America BUT ONLY WHEN it's the only country in the list, not when there are other countries like example a.

I tried to brainstorm and came up with something like this:

countryToRemove = "United States of America"
for index, row in df.iterrows():
    if countryToRemove in row['countries']:
        # row to be removed

But it deletes any row with the US in it even if other countries were there.

Edit: My dataframe is as following:

countries
0  [{'iso_3166_1': 'DE', 'name': 'Germany'}, {'is...
1  [{'iso_3166_1': 'US', 'name': 'United States o...
2                                                 []
1 Answers

If you have dataframe like this:

                                           countries
0  [{'iso_3166_1': 'DE', 'name': 'Germany'}, {'is...
1  [{'iso_3166_1': 'US', 'name': 'United States o...
2                                                 []

Then you can use boolean indexing to filter out your dataframe:

mask = df.countries.apply(
    lambda x: len(s := set(d["name"] for d in x)) == 1
    and s.pop() == "United States of America"
)
print(df[~mask])

Prints:

                                           countries
0  [{'iso_3166_1': 'DE', 'name': 'Germany'}, {'is...
2                                                 []

EDIT: Version without := operator:

def fn(x):
    s = set(d["name"] for d in x)
    return len(s) == 1 and s.pop() == "United States of America"


mask = df.countries.apply(fn)
print(df[~mask])
Related