我的数据框中的一列是字典列表,类似于这样:
如何过滤标签列中 id 键具有特定值的行?例如包含 {"id": 18}
的行最佳答案
由于您的 tag
列是列表值的,如果您使用的是 pandas 0.25+,则可以使用 explode
:
# toy data
df = pd.DataFrame({'type':['df','fg','ff'],
'tag': [[{"id" : 12} ,{"id" : 13}],
[{"id" : 12}],
[{'id':10}]]
})
# make each row contains exactly one dict: {id: val}
s = df['tag'].explode()
# the indexes of interested rows
idx = s.index[pd.DataFrame(s.to_list())['id'].values==12]
# output
df.loc[idx]
输出:
type tag
0 df [{'id': 12}, {'id': 13}]
1 fg [{'id': 12}]
关于python - 数据框中字典列的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58438132/