如何根据列表中字典列字段的键值对过滤DataFrame行?

4
我有一个包含很多字典的数据框,其中一个列/字段是字典的长列表。我想只保留数据框的子集中包含特定字典条目的行。我不想过滤字典列表,只想检索包含所需条目(通常还有许多其他条目)的行,并保持所有其他列/字段不变。
以下是模拟数据框:
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示例的伪代码...

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

1个回答

3

将其转换为字符串然后使用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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接