首页 > 解决方案 > 使用循环从数据框中删除行

问题描述

我有一个世界上每个国家的环境数据数据框。我想删除任何不代表个别国家的国家条目,即“非洲”或“世界”。我已经列出了这些值。我正在尝试遍历 df 并删除列表中国家 = 值的每一行。没有那么多问题条目,我之前用 .loc 删除了它们,但我不确定为什么这个函数不起作用。我收到一个错误:KeyError: '[(bunch of numbers)] not found in axis'

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) ```

标签: pythonpandas

解决方案


数据框的优点之一是您很少需要遍历它来完成工作。通常有更有效的方法。这是使用带有世界人口数据的示例数据框来解决您的问题的方法。

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

推荐阅读