【问题标题】:Is there a way to check if a list item is the ONLY item in the list?有没有办法检查列表项是否是列表中的唯一项?
【发布时间】:2021-07-23 07:23:59
【问题描述】:

我有一个字典列表,整个列表代表不同的国家,每个字典包含每个国家的基本数据如下: 示例

df.countries[3]
"[{'iso_3166_1': 'DE', 'name': 'Germany'}, {'iso_3166_1': 'US', 'name': 'United States of America'}, {'iso_3166_1': 'IN', 'name': 'India'}]"

当然,还有其他单元格,其中国家列表只有一个字典,如下所示: 示例 b

df.countries[0]
"[{'iso_3166_1': 'US', 'name': 'United States of America'}]"

或者像这样的空列表: 示例 c

df.countries[505]
'[]'

我想做的是:

  • 删除国家名称为 United States of America BUT 的行 仅当它是列表中唯一的国家时,而不是当有 其他国家,例如 a

我试图集思广益并想出了这样的事情:

countryToRemove = "United States of America"
for index, row in df.iterrows():
    if countryToRemove in row['countries']:
        # row to be removed

但即使其他国家/地区存在,它也会删除其中包含美国的任何行。

编辑:我的数据框如下:

countries
0  [{'iso_3166_1': 'DE', 'name': 'Germany'}, {'is...
1  [{'iso_3166_1': 'US', 'name': 'United States o...
2                                                 []

【问题讨论】:

  • 请在序列(列表、元组等)上重复您的教程材料,并学习每种数据类型的基本方法。在这里,您还需要检查列表长度是否为 1。
  • 您能否编辑您的问题,以便我们重现您的问题? This might be a useful resource for that purpose.

标签: python pandas list dictionary data-structures


【解决方案1】:

如果你有这样的数据框:

                                           countries
0  [{'iso_3166_1': 'DE', 'name': 'Germany'}, {'is...
1  [{'iso_3166_1': 'US', 'name': 'United States o...
2                                                 []

然后您可以使用布尔索引来过滤掉您的数据框:

mask = df.countries.apply(
    lambda x: len(s := set(d["name"] for d in x)) == 1
    and s.pop() == "United States of America"
)
print(df[~mask])

打印:

                                           countries
0  [{'iso_3166_1': 'DE', 'name': 'Germany'}, {'is...
2                                                 []

编辑:没有:= 运算符的版本:

def fn(x):
    s = set(d["name"] for d in x)
    return len(s) == 1 and s.pop() == "United States of America"


mask = df.countries.apply(fn)
print(df[~mask])

【讨论】:

  • 是的,数据框与您输入的一样。我尝试了您的解决方案,但出现以下错误: File "", line 2 lambda x: len(s: set(d["name"] for d in x)) == 1 ^ SyntaxError: 无效语法
  • @FatimahE。您正在使用旧版本的 Python。查看我的编辑。
猜你喜欢
  • 2010-12-03
  • 2015-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-10
  • 2022-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多