我有世界上每个国家的环境数据框架。我想删除任何不代表单个国家的国家的条目,即“非洲”或“世界”。我已经列出了这些值。我正在尝试遍历df并删除列表中国家=a值的每一行。没有那么多的问题条目,我以前用.loc删除过它们,但我不确定为什么这个函数不能工作。我得到一个错误:
KeyError:‘
(一堆数字)
在轴‘中找不到
not_country = ['Africa', 'Asia', 'Asia (excl. China & India)','EU-27','EU-28', 'Europe','Europe (excl. EU-27)',
'Europe (excl. EU-28)', 'International transport', 'Kuwaiti Oil Fires', 'North America',
'North America (excl. USA)', 'World', 'South America']
def clean_countries(df, lst):
index_names = []
for country_name in lst:
index_names.append(df[df['country'] == country_name].index)
for i in df:
df.drop(index_names, inplace = True)
clean_co2_df = clean_countries(co2_df, not_country) ```
发布于 2021-03-01 07:34:03
dataframe的优点之一是,您很少需要遍历它来完成工作。通常有更有效的方法。以下是使用包含世界人口数据的样本数据帧对您的问题的解决方案。
not_country = ['Africa', 'Asia', 'Asia (excl. China & India)','EU-27','EU-28', 'Europe','Europe (excl. EU-27)',
'Europe (excl. EU-28)', 'International transport', 'Kuwaiti Oil Fires', 'North America',
'North America (excl. USA)', 'World', 'South America']
pop_data = {'Country': {0: 'China', 1: 'India', 2: 'USA', 3: 'Asia'}, 'Population': {0: 1439000000, 1: 1380004385, 2: 331002651, 3: 4641054775}, 'Yearly Change %': {0: 0.39, 1: 0.99, 2: 0.59, 3: 0.86}}
df = pd.DataFrame(pop_data)
print(f'BEFORE: \n {df}')
df = df.loc[df['Country'].apply(lambda x: x not in not_country)]
print(f'AFTER: \n {df}')
#output:
BEFORE:
Country Population Yearly Change %
0 China 1439000000 0.39
1 India 1380004385 0.99
2 USA 331002651 0.59
3 Asia 4641054775 0.86
AFTER:
Country Population Yearly Change %
0 China 1439000000 0.39
1 India 1380004385 0.99
2 USA 331002651 0.59
https://stackoverflow.com/questions/66414488
复制相似问题