字典列表中的熊猫字符串搜索

时间:2019-08-17 08:33:50

标签: python pandas

如何在以下Pandas数据框中搜索字符串'data1'

在这里可以找到字符串:

df.test[0][0]['term']
'data1'

有关数据帧结构的其他信息:

df.test[0]

[{'term': 'data1', 'a': "foo", 'b': "bar"},
 {'term': 'data2' ,'a': "foo", 'b': "bar"}]

type(df.test)
pandas.core.series.Series

type(df.test[0])
list

type(df.test[0][0])
dict

我尝试了什么?

我很欣赏需要df.test.str.contains('Data1')之类的东西,但是我不确定如何使用嵌套列表/ dict数据结构来做到这一点

1 个答案:

答案 0 :(得分:2)

最简单的方法是将其转换为字符串,因此通过字典列表的字符串表示形式进行测试:

df.test.astype(str).str.contains('data1')

如果需要通过term键进行测试:

df['test'].apply(lambda x: any(y.get('term') == 'data1' for y in x))

或所有dict值:

df['test'].apply(lambda x: any('data1' in y.values() for y in x))

示例

a = [{'term': 'data1', 'a': "foo", 'b': "bar"},
 {'term': 'data2' ,'a': "foo", 'b': "bar"}]
b = [{'term': 'data4', 'a': "foo", 'b': "bar"},
 {'term': 'data2' ,'a': "foo", 'b': "bar"}]
df = pd.DataFrame({"test": [a, b]})
print (df)
                                                test
0  [{'term': 'data1', 'a': 'foo', 'b': 'bar'}, {'...
1  [{'term': 'data4', 'a': 'foo', 'b': 'bar'}, {'...

print (df.test.astype(str).str.contains('data1'))
0     True
1    False
Name: test, dtype: bool

print (df['test'].apply(lambda x: any(y.get('term') == 'data1' for y in x)))
0     True
1    False
Name: test, dtype: bool

print (df['test'].apply(lambda x: any('data1' in y.values() for y in x)))
0     True
1    False
Name: test, dtype: bool