python - 如何将 Python 数据框对象转换为 json?
问题描述
我有一个这样的数据框:
date ... ID value_1 value_2 value_3
0 03/03/2018 ... 12345 111 1 30
1 03/03/2018 ... 89547 222 2 50
2 02/03/2018 ... 12345 333 5 80
我想将其转换为 JSON 格式,如下所示:
{
"XYZ": [
{
"Id": 123456,
"date": "2021-03-03 09:00:00", # this field need to change datetime format
"value_3": 30,
"value_2": 1,
"ABC": [
{
"value_1": 111,
"type": "int" # 'type' field will always be 'int'
}
]
},
{
"Id": 123456,
"date": "2021-03-02 09:00:00", # this field need to change datetime format
"value_3": 80,
"value_2": 5,
"ABC": [
{
"value_1": 333,
"type": "int" # 'type' field will always be 'int'
}
]
},
{
"Id": 89547,
"date": "2021-03-03 09:00:00", # this field need to change datetime format
"value_3": 50,
"value_2": 2,
"ABC": [
{
"value_1": 222,
"type": "int" # 'type' field will always be 'int'
}
]
}
]
}
我对 Python 中的数据操作不是很熟悉,有没有一种简单的方法来进行转换(内置函数或任何库?)?非常感谢。
解决方案
利用:
import json
#convert values to datetimes
df['documentdate'] = pd.to_datetime(df['documentdate'], dayfirst=True, errors='coerce')
#change format of ABC
df['ABC'] = df['value_1'].apply(lambda x: [ {"value_1": x, "type": "int" }])
#remove columns
df = df.drop('value_1', axis=1)
#convert to dict and then to json
j = json.dumps({"XYZ":df.to_dict(orient='records')}, default=str)
print (j)
编辑:
对于转换日期时间,也可以使用:
#https://stackoverflow.com/a/11875813/2901002
from bson import json_util
import json
json.dumps({"XYZ":df.to_dict(orient='records')}, default=json_util.default)
推荐阅读
- bash - 在我的主目录下查找超过一定大小的文件
- java - hashmap 如何识别何时需要重新散列
- c# - 将平面数据库行数据转换为嵌套类型对象 linq
- angular - 提交表单时如何隐藏选项面板?
- javascript - JavaScript 不在 Instagram 应用程序中运行?
- excel - VBA按多个条件剪切和粘贴行
- symfony - 如何确定 key 是否是对象(树枝)?
- math - 在 Markdown 中,以数学为中心的环境会出错
- python-3.x - Python - 使用 autoit 自动启动 Chrome 并在地址栏中输入 URL
- c# - 如何设置触发器以在 Unity3D 中制作可交互对象?