3 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以使用json_normalize
:
df = pd.io.json.json_normalize(s)
print(df)
? ? name? points? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?tags
0? first? ? ?0.5? ? ? ? ? ?[{'key': 'Owner', 'value': 'A'}]
1? first? ? ?1.5? ? ? ? ? ?[{'key': 'Owner', 'value': 'B'}]
2? first? ? 24.0? [{'key': 'SomeOtherTag', 'value': 'XYZ'}]
# to filter
filter_mask = df['tags'].apply(lambda x: x[0]['value'] == 'A')
df.loc[filter_mask, "points"].sum()

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
如果您不嚴(yán)格使用 Pandas,另一種方法是對(duì)生成器理解求和,假設(shè)tags
每行列表中只嵌入一個(gè)字典:
sum(entry["points"] for entry in data if entry["tags"][0]["value"] == "A") 0.5

TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超7個(gè)贊
json_normalize()為你做這一切
js = [{'name': 'first', 'points': 0.5, 'tags': [{'key': 'Owner', 'value': 'A'}]},
{'name': 'first', 'points': 1.5, 'tags': [{'key': 'Owner', 'value': 'B'}]},
{'name': 'first',
'points': 24,
'tags': [{'key': 'SomeOtherTag', 'value': 'XYZ'}]}]
pd.json_normalize(js, record_path="tags", meta=[['name'], ['points']])
輸出
key value name points
Owner A first 0.5
Owner B first 1.5
SomeOtherTag XYZ first 24
補(bǔ)充更新
如果從文件中讀取
import json
with open('all_items.json') as f: items = json.load(f)
pd.json_normalize(items, record_path="tags", meta=[['name'], ['points']])
添加回答
舉報(bào)