【问题标题】:Pandas transform json column into multiple columnsPandas 将 json 列转换为多列
【发布时间】:2022-01-03 18:06:57
【问题描述】:

我需要将列中带有 json 值的以下数据框转换为数据框列式结构,以便占用更少的空间并易于计算。

示例数据帧:

obs_id date obs
I2213 2021-12-31 23:20:02.761008 "[{'type': 'air', 'results': {'bat': {'F1': 0.1, 'F2': 0.2}}, {'type': 'water', 'results': {'neo': {'F1': 0.3}}]"
I2213 2022-01-01 23:20:02.761008 "[{'type': 'earth', 'results': {'cat': {'F1': 0.4}}]"
I2213 2022-01-02 23:20:02.761008 "[{'type': 'air', 'results': {'bat': {'F1': 0.2, 'F2': 0.1}}]"

所需的转换格式:

obs_id date obs.air.bat.F1 obs.air.bat.F2 obs.water.neo.F1 obs.earth.cat.F1

不确定多级列是否更适合这里。

我尝试从 obs 列创建一个单独的数据框,例如:

df1 = pd.DataFrame(df['obs'].values.tolist())

但由于它包含列表而不是字典,所以它不起作用。 能不能达到要求的格式?

【问题讨论】:

  • obs 是字符串?

标签: python json pandas dataframe


【解决方案1】:

让我们从更正您的源数据开始。 由于您的样本包含不平衡的括号,因此可能是其实际内容 应该是:

   obs_id  date        obs
0  I2213   2021-12-31  [{'type': 'air', 'results': {'bat': {'F1': 0.1, 'F2': 0.2}}}, {'type': 'water', 'results': {'neo': {'F1': 0.3}}}]
1  I2213   2022-01-01  [{'type': 'earth', 'results': {'cat': {'F1': 0.4}}}]
2  I2213   2022-01-02  [{'type': 'air', 'results': {'bat': {'F1': 0.2, 'F2': 0.1}}}]

为了保持打印输出的合理宽度,我从您的 date 列中删除了时间部分。

从必要的导入开始编码部分:

import pandas as pd
import json

然后定义一个行处理函数为:

def procRow(row):
    wrk1 = pd.json_normalize(json.loads(row.obs.replace("'", '"')))
    wrk2 = wrk1.set_index('type').stack().reset_index()
    return pd.Series(wrk2[0].values, index='obs.' + wrk2.type\
        + wrk2.level_1.str.slice(7))

并将 df 的前 2 列与应用的结果连接起来 每一行的函数:

result = pd.concat([df.iloc[:, 0:2], df.apply(procRow, axis=1)], axis=1)

结果是:

  obs_id       date  obs.air.bat.F1  obs.air.bat.F2  obs.earth.cat.F1  obs.water.neo.F1
0  I2213 2021-12-31             0.1             0.2               NaN               0.3
1  I2213 2022-01-01             NaN             NaN               0.4               NaN
2  I2213 2022-01-02             0.2             0.1               NaN               NaN

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-19
    • 2020-03-21
    • 2021-11-08
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 2017-05-01
    相关资源
    最近更新 更多