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

标签 python pandas

考虑以下示例

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/

相关文章:

python - 如何添加多个具有固定值的新列?

python - 跨行分组正则表达式并在 pandas 中聚合

python - Pyqt5:单击事件时在 QlineEdit 框中动态传递值

python - 将字典作为值分配给字典键

python - 如何在 python 中使用 matplotlib 和 pandas 绘制 CSV 数据

python - 如何通过 'Exclude' 条件创建行并扩展到现有的 Dataframe 中?

python - 如何根据条件从另一个数据框中仅替换某些列值?

python - Lark 解析器无法解析字符,即使它们是在规则的正则表达式中定义的

python - 合并备用索引组合处的 n 元组列表

python - reportlab TableStyle 中的 VALIGN 显然没有效果