Deleting groups of countries from dataframe indexes

Viewed 201

I have a dataframe, where I have set indexes as countries. However there are also groups of countries such as Sub-Saharan Africa (IDA & IBRD countries) or Middle East & North Africa (IDA & IBRD countries). I want to delete them. I want just countries to stay.

Example imput dataframe where indexes are:

Antigua and Barbuda
Angola
Arab World

Wanted output dataframe:

Antigua and Barbuda
Angola

My idea was using pycountry, however it does nothing.

countr=list(pycountry.countries)
for idx in df.index:
    if idx in countr :
            continue
    else:
        df.drop(index=idx)
1 Answers

Check your list of country names:

countries_list = []
for country in pycountry.countries:
    countries_list.append(country.name)

Checking output:

>>> print(countries_list[0:5])
['Aruba', 'Afghanistan', 'Angola', 'Anguilla', 'Åland Islands']

You can do this if you want to get a dataframe of countries that are in your countries list:

import pycountry
import pandas as pd


country = {'Country Name': ['Antigua and Barbuda','USSR', 'United States', 'Germany','The Moon']}
df = pd.DataFrame(data=country)

countries_list = []
for country in pycountry.countries:
    countries_list.append(country.name)

new_df = []

for i in df['Country Name']:
    if i in countries_list:
        new_df.append(i)

Checking output:

>>> print(new_df)
['Antigua and Barbuda', 'United States', 'Germany']

Otherwise, for your specific code, try this:

Assuming you have your data in a dataframe 'df':

import pandas as pd
import pycountry

countries_list = []
for country in pycountry.countries:
    countries_list.append(country.name)

for idx in df.index:
    if idx in countries_list:
            continue
    else:
        df.drop(index=idx)

Let me know if this works for you.

Related