首页 > 解决方案 > Pandas 解析 json 列并将现有列保存到新数据框中

问题描述

我有以下数据框:

name  stats
smith {"eye_color": "brown", "height": 160, "weight": 76}
jones {"eye_color": "blue", "height": 170, "weight": 85}
will  {"eye_color": "green", "height": 180, "weight": 94}

我使用以下代码将 json 字段解析为新的数据帧:

new_df = df["stats"].apply(json.loads).apply(pd.Series)

这给了我new_df

eye_color height weight
brown     160    76
blue      170    85
green     180    94

如何更新上面添加的代码namenew_df以便我拥有:

name  eye_color height weight
smith brown     160    76
jones blue      170    85
will  green     180    94

标签: pythonpython-3.xpandas

解决方案


使用df.join()

new_df=df[['name']].join(df["stats"].apply(json.loads).apply(pd.Series))

推荐阅读