从数据帧索引中删除国家组

2024-04-29 02:01:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框架,其中我将索引设置为国家。然而,也有一些国家集团,如撒哈拉以南非洲(IDA和IBRD国家)或中东和非洲;北非(国际开发协会和国际复兴开发银行国家)。我想删除它们。我只想留下来

输入数据框示例,其中索引为:

Antigua and Barbuda
Angola
Arab World

想要的输出数据帧:

Antigua and Barbuda
Angola

我的想法是使用pycountry,但它没有任何作用

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

Tags: and数据in框架dfindex国家集团
1条回答
网友
1楼 · 发布于 2024-04-29 02:01:32

检查您的国家/地区名称列表:

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

检查输出:

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

如果要获取国家/地区列表中国家/地区的数据框,可以执行此操作:

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)

检查输出:

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

否则,对于特定代码,请尝试以下操作:

假设您的数据位于数据帧“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)

让我知道这是否适合你

相关问题 更多 >