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

如何将Pandas Core Series转换为独立的多列?

如何将Pandas Series中的嵌套字典列表归一化为独立列?

核心解决方案

根据你提供的df['locations']结构(每个元素是包含字典的列表),分两种场景处理:

场景1:每个列表仅包含单个字典

这是你示例中呈现的情况,可直接提取字典并展开为列:

# 提取列表内的字典并转为DataFrame
locations_df = df['locations'].apply(lambda x: x[0]).apply(pd.Series)
# 与原DataFrame合并,移除原locations列
df_final = pd.concat([df.drop('locations', axis=1), locations_df], axis=1)

或者更简洁的方式,直接用pd.json_normalize处理:

locations_df = pd.json_normalize(df['locations'])
df_final = pd.concat([df.drop('locations', axis=1), locations_df], axis=1)

场景2:每个列表包含多个字典

如果需要将列表中的每个字典展开为单独行,同时保留原数据的其他字段:

# 将列表拆分为多行
df_exploded = df.explode('locations').reset_index(drop=True)
# 展开字典为列并合并
df_final = pd.concat([df_exploded.drop('locations', axis=1), df_exploded['locations'].apply(pd.Series)], axis=1)

你之前操作的问题说明

  • pd.DataFrame([df['locations']])得到1行196列:是因为你把整个Series包装成了一个列表元素,Pandas会将Series的每个索引值作为列,每个元素作为单元格值,这并非字典展开的逻辑。
  • to_string()转换后报错:to_string()返回的是纯文本字符串,无法直接作为DataFrame构造器的输入,因此触发ValueError。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:25:28