【问题标题】:How do I filter DataFrame rows based on a key value pair from a list of dictionaries column field?如何根据字典列字段列表中的键值对过滤 DataFrame 行?
【发布时间】:2020-07-17 03:29:46
【问题描述】:

我有一个 DataFrame,其中一列/字段是一长串字典。我只想将行保留在字典列表包含某个字典条目的 DataFrame 子集中。我不想过滤字典列表,只需检索存在所需条目的行(通常在许多其他条目中),保持所有其他列/字段不变。

这是一个模拟 df

df = pd.DataFrame({'bird': ['robin', 'jay', 'pelican', 'duck'], 'beaky': ['yes', 'yes', 'yes', 'yes'], 'feathers': [[{'type':'thing', 'id':'1a'}, {'type':'thing', 'id':'5a'}] , [{'type': 'thing', 'id':'2a'},{'type':'thing', 'id':'1a'}],[{'type': 'thing', 'id':'3a'},{'type': 'thing', 'id':'4a'}],[{'type':'thing', 'id':'2a'}, {'type':'thing', 'id':'3a'}]]})

df

上面 df 示例的伪代码...

选择 df['feathers'] 包含 {'type': 'thing', 'id': '3a'} 的 DataFrame 行

【问题讨论】:

    标签: python pandas dictionary


    【解决方案1】:

    转换为字符串然后str.contains

    m=df.feathers.astype(str).str.contains("{'type': 'thing', 'id': '3a'}")
    0    False
    1    False
    2     True
    3     True
    Name: feathers, dtype: bool
    df=df[m]
    

    【讨论】:

      猜你喜欢
      • 2020-02-06
      • 2015-05-17
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 2019-01-23
      • 2012-05-16
      相关资源
      最近更新 更多