简体   繁体   English

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

[英]How do I filter DataFrame rows based on a key value pair from a list of dictionaries column field?

I have a DataFrame where one column/field is a long list of dictionaries.我有一个 DataFrame ,其中一列/字段是一长串字典。 I want to only keep rows in a subset of the DataFrame where the list of dictionaries contains a certain dictionary entry.我只想将行保留在 DataFrame 的子集中,其中字典列表包含某个字典条目。 I don't want to filter the list of dictionaries, just retrieve rows where the desired entry exists (usually among many other entries) keeping all other columns/fields intact.我不想过滤字典列表,只需检索存在所需条目的行(通常在许多其他条目中),保持所有其他列/字段不变。

Here's a mock df这是一个模拟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

Pseudo code for the df example above...上面 df 示例的伪代码...

Select rows of the DataFrame where df['feathers'] contains {'type': 'thing', 'id': '3a'} DataFrame 的 Select 行,其中 df['feathers'] 包含 {'type': 'thing', 'id': '3a'}

Convert to string then str.contains转换为字符串然后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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据匹配的键:值对组合字典列表中的 N 个字典? - how do I combine N dictionaries in list of dictionaries based on matching key:value pair? 如何将新的键值对添加到字典列表中? - How do I add a new key value pair to a list of dictionaries? 如何从包含键作为字典列表的字典中获取第一个键值对(即“类型”:45) - How do i fetch first key value pair (i.e., 'type': 45) from a dictionary which contains key as list with dictionaries 在 pandas dataframe 中,如何根据列值过滤行,进行计算并将结果分配给新列? - In a pandas dataframe, how can I filter the rows based on a column value, do calculation and assign the result to a new column? 根据匹配的键值对组合字典列表中的字典 - combine dictionaries in list of dictionaries based on matching key:value pair 如何基于以列表为值的列在Pandas数据框中过滤行? - How do I filter for rows in a Pandas dataframe based on a column that has list as values? 如何检查任何键值对是否在字典列表中多次出现? - How do I check if any key-value pair appears more than once in a list of dictionaries? 如何根据 Python 列表中的列号过滤数据框中的行? - How do you filter rows in a dataframe based on the column numbers from a Python list? 如何根据具有两个键值对的词典列表中的另一个kv对的值创建一个键值对中的值列表 - how to create a list of values from one key-value pair based on the value of another k-v pair from a list of dictionaries with two key-value pairs 如何根据 Python 中的公共键值对有效地将键值从一个字典列表插入另一个字典列表? - How to efficiently insert key-value from one list of dictionaries to another based on a common key-value pair in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM