You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何展平pandas DataFrame中经json_normalize处理后仍含列表的JSON列

解决方案

你可以组合使用pandas的explode()和json_normalize()两步完成扁平化,具体代码如下:

import pandas as pd

# 假设你现有的DataFrame变量名为df
# 第一步:把列表类型的目标列拆分成单行字典
df_exploded = df.explode("totalPageStatistics.clicks.mobileCustomButtonClickCounts", ignore_index=True)

# 第二步:把单行字典展开为多列
df_flat = pd.json_normalize(df_exploded["totalPageStatistics.clicks.mobileCustomButtonClickCounts"])

# 第三步:合并原有org列+展开后的列,并重命名为目标格式
result = pd.concat([df_exploded[["org"]], df_flat], axis=1)
result.columns = [
    "org",
    "mobileCustomButtonClickCountsButtonType",
    "mobileCustomButtonClickCountsClicks"
]

如果偏好链式写法,可以合并成一段:

result = (
    df.explode("totalPageStatistics.clicks.mobileCustomButtonClickCounts", ignore_index=True)
    .assign(**pd.json_normalize(_["totalPageStatistics.clicks.mobileCustomButtonClickCounts"]))
    .rename(columns={
        "customButtonType": "mobileCustomButtonClickCountsButtonType",
        "clicks": "mobileCustomButtonClickCountsClicks"
    })
    [["org", "mobileCustomButtonClickCountsButtonType", "mobileCustomButtonClickCountsClicks"]]
)

原理说明

  • explode()会把列表里的每个元素单独拆成一行,其他列(比如org)的取值会对应保留,不会错乱
  • json_normalize()会把每行的字典按键拆分为独立的列,自动匹配对应的值
  • 最后拼接、重命名列即可完全匹配你需要的输出格式

内容的提问来源于stack exchange,提问作者Krouse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 12:39:02