【问题标题】:Appending list from dataframe with for statement使用 for 语句从数据框中附加列表
【发布时间】:2021-02-07 15:50:57
【问题描述】:

在学校学习 Python。在一个项目上工作,我想从一个数据框中删除特定的行并将其转换为另一个数据框。我有一个包含 372 只动物的列表,如果它们的名字出现在数据框中(其中有 1288 行,每行是不同的动物),我想删除该行。因此,我找到了删除行的解决方案:

ess_aza = []

for i in aza_names:
    if True:
        ess_aza.append(ess_clean.loc[ess_clean['scientific_name'] == i])
    else:
        return

列表打印出来后的样子是这样的:

[Empty DataFrame
Columns: [common_name, scientific_name, status]
Index: [],   common_name      scientific_name      status
0       Addax  Addax nasomaculatus  Endangered, Empty DataFrame
Columns: [common_name, scientific_name, status]
Index: [],           common_name     scientific_name      status
1  Alligator, Chinese  Alligator sinensis  Endangered,      common_name         scientific_name      status
1  Anoa, lowland  Bubalus depressicornis  Endangered, Empty DataFrame
Columns: [common_name, scientific_name, status]
Index: [], Empty DataFrame
Columns: [common_name, scientific_name, status]
Index: [], Empty DataFrame
Columns: [common_name, scientific_name, status]
Index: [], ,....

我对 Python 的了解还不够,不知道为什么它会给我这样的输出。据我所知,它正在返回所有 1288 行的数据,并为与列表不匹配的所有行返回“空数据帧列:[common_name,science_name,status] Index:[]”。

我怎样才能阻止这种情况的发生,只需在列表中添加我需要的行? (或者更好的是只使用我需要的行创建一个新数据框。这就是最终目标。)

【问题讨论】:

    标签: python pandas list dataframe append


    【解决方案1】:

    如果您有要排除的行列表,请尝试以下操作:

    clean_df = df[~df['scientific_name'].isin(excludeRows)]
    

    获取排除行的df

    clean_df = df[df['scientific_name'].isin(excludeRows)]
    

    clean_df 是你的新 df,df 是旧的, excludeRows 是要排除的行值。

    【讨论】:

    • AAH 谢谢你完美的工作!你能解释一下 ~ 在这行代码中扮演什么角色吗?
    • 这叫做布尔过滤,~否定条件
    • 哦等等!显然它把我需要的动物从数据框中取出,而 clean_df 是剩下的动物。所以,我删除了 ~ 并且它起作用了。谢谢!
    • 已编辑请检查
    猜你喜欢
    • 2021-08-24
    • 2017-02-17
    • 2015-09-07
    • 1970-01-01
    • 2018-03-05
    • 2021-05-29
    • 1970-01-01
    • 2017-12-23
    • 2019-04-11
    相关资源
    最近更新 更多