python - 将 DataFrame 列转换为 json 列
问题描述
我有一个熊猫数据框,其中一列是 json 类型,但如下所示:列 {1:1,2:2,3:3}
但我希望这是真正的 json 格式,如列 {"1":1,"2":2,"3":3}
目前该列的数据类型是对象
解决方案
这应该有效:
import ast
import json
import pandas
def convert_json(row: pandas.Series) -> pandas.Series:
# Read the string as a python dictionary (literal_eval), then, turn the key into a string, then dump as a valid JSON string
row["real_json"] = json.dumps({str(key): value for key, value in ast.literal_eval(row["my_json"]).items()})
# Return the row
return row
# Some test data
df = pandas.DataFrame([{"my_json": "{1:1,2:2,3:3}"} for _ in range(10)])
# Loop the rows and apply the function
df = df.apply(convert_json, axis=1)
输出:
print(df)
my_json real_json
0 {1:1,2:2,3:3} {"1": 1, "2": 2, "3": 3}
1 {1:1,2:2,3:3} {"1": 1, "2": 2, "3": 3}
2 {1:1,2:2,3:3} {"1": 1, "2": 2, "3": 3}
3 {1:1,2:2,3:3} {"1": 1, "2": 2, "3": 3}
4 {1:1,2:2,3:3} {"1": 1, "2": 2, "3": 3}
5 {1:1,2:2,3:3} {"1": 1, "2": 2, "3": 3}
6 {1:1,2:2,3:3} {"1": 1, "2": 2, "3": 3}
7 {1:1,2:2,3:3} {"1": 1, "2": 2, "3": 3}
8 {1:1,2:2,3:3} {"1": 1, "2": 2, "3": 3}
9 {1:1,2:2,3:3} {"1": 1, "2": 2, "3": 3}
推荐阅读
- c# - SQL 显示结果中的 DGV 查找文件名
- python - Redis Python execute_command Redisearch
- react-redux - 无法从 Normalizr 获取实体
- ionic4 - ionic4 App - 登陆页面在启动期间加载控制器页面之前显示几毫秒
- php - 如何在自动完成输入中显示数据库中的多个字段
- javascript - export { default as Module } from './Module' 没有为 IE11 正确转译
- string - 获取两个字符串之间的子字符串
- sql-server - SQL Server 2008 透视文本列太大
- c# - Unity Dark Rift Online 事件 Args 问题
- java - 将通配符元素添加到通用容器类