python - 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
如何更新上面添加的代码name
,new_df
以便我拥有:
name eye_color height weight
smith brown 160 76
jones blue 170 85
will green 180 94
解决方案
使用df.join()
:
new_df=df[['name']].join(df["stats"].apply(json.loads).apply(pd.Series))
推荐阅读
- r - 如何使用 knitr 和 pandoc 正确设置子文档中的图像路径
- html - 模糊效果不会覆盖整个元素(导航栏)
- inheritance - 无法从继承 NFT 合约的单独合约访问 ERC721 OpenZeppelin NFT
- python - AttributeError:“函数”对象没有属性“提交”
- mongodb - 带有条件的 Arrayof Ids 上的 MongoDB $lookup
- python - PYMQI 与 IBM MQ 客户端 Docker 容器
- druid - Druid 摄取问题 - 内存分配
- reactjs - 即使在分配值之后,useLocation 中的状态也未定义
- hyperledger-fabric - 如果 Hyperledger Fabric 网络中 Peer 的账本被篡改,如何恢复账本之前的状态?
- oracle - 将 varbinary 数据加载到 oracle 原始列时出错