[英]Pandas: Select rows whose dictionary contains a specific key
I have a dataframe, in which one column is all dictionary. 我有一个数据框,其中一列都是字典。 I want to select rows whose dictionary contains a given key. 我想选择其字典包含给定键的行。
>>> df = pd.DataFrame({"A": [1,2,3], "B": [{"a":1}, {"b":2}, {"c":3}]})
>>> df
A B
0 1 {'a': 1}
1 2 {'b': 2}
2 3 {'c': 3}
>>> df['b' in df['B']]
# the desired result is the row with index 1. But this causes an error: KeyError: False
Here is one way: 这是一种方法:
df = pd.DataFrame({"A": [1,2,3], "B": [{"a":1}, {"b":2}, {"c":3}]})
df = df[df['B'].map(lambda x: 'b' in x)]
# A B
# 1 2 {'b': 2}
Explanation 说明
pd.Series.map
accepts anonymous ( lambda
) functions as an argument. pd.Series.map
接受匿名( lambda
)函数作为参数。 B
and checks whether b
is in that element, returning a Boolean series. 该函数获取B
每个元素,并检查b
是否在该元素中,并返回一个布尔序列。 df[bool_series]
to choose the required rows. 我们使用df[bool_series]
的自然df[bool_series]
选择所需的行。 Using get the dict keys 使用获取字典键
df.B.apply(lambda x : 'b' in x.keys())
Out[89]:
0 False
1 True
2 False
Name: B, dtype: bool
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.