熊猫:选择字典中包含特定键的行

Mun*_*ong 2 python dictionary dataframe pandas

我有一个数据框,其中一列都是字典。我想选择其字典包含给定键的行。

>>> 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
Run Code Online (Sandbox Code Playgroud)

jpp*_*jpp 5

这是一种方法:

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}
Run Code Online (Sandbox Code Playgroud)

说明

  • pd.Series.map接受匿名(lambda)函数作为参数。
  • 该函数接受的每个元素,B并检查是否b在该元素中,并返回一个布尔序列。
  • 我们使用的自然布尔索引来df[bool_series]选择所需的行。