gpt4 book ai didi

python - 如何有效地从 JSON 列中提取字段?

转载 作者:行者123 更新时间:2023-11-30 21:53:48 24 4
gpt4 key购买 nike

考虑以下示例

data1 = [{'type': 'one', 'delta': '1', 'time': '2019'}, {'type': 'two', 'delta': '1', 'time': '2018'}]
data2 = [{'type': 'one', 'delta': '1', 'time': '2013'}, {'type': 'two', 'delta': '1', 'time': '2012'}]


dftest = pd.DataFrame({'weirdjson' : [data1, data2]})
dftest['normalcol'] = 1

dftest

Out[79]:
weirdjson normalcol time_type_one time_type_two
0 [{'type': 'one', 'delta': '1', 'time': '2019'}, {'type': 'two', 'delta': '1', 'time': '2018'}] 1 2019 2018
1 [{'type': 'one', 'delta': '1', 'time': '2013'}, {'type': 'two', 'delta': '1', 'time': '2012'}] 1 2013 2012

本质上,我想创建两列 time_type_onetime_type_two,每列都包含相应的 time 值(对于第一行:<2019 表示类型一2018 表示类型二)。

我怎样才能在 Pandas 中做到这一点?我有很多行,所以我正在寻找非常有效的东西。谢谢!

最佳答案

您可以使用explode,并构造一个新的数据框和unstack类型到列,如下所示:

s = dftest.weirdjson.explode()
df_new = (pd.DataFrame({'type': s.str['type'], 'time': s.str['time']})
.set_index('type', append=True).time.unstack().add_prefix('time_type_'))

Out[461]:
type time_type_one time_type_two
0 2019 2018
1 2013 2012

关于python - 如何有效地从 JSON 列中提取字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59522816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com