欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

pandas读取json文件 Python

程序员文章站 2022-04-02 10:47:10
pandas读取json文件 Pythonjson文件中的内容如下:[{"mac": 1,"timestamp": 1307386437,"volt": 2.5,"temp": 35.5,"acc": [[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3]],"sampletime":1307386437},{"mac": 1,"timestamp": 1...

pandas读取json文件 Python


json文件中的内容如下:

[
{"mac": 1,"timestamp": 1307386437,"volt": 2.5,"temp": 35.5,"acc": [[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3]],"sampletime":1307386437},
{"mac": 2,"timestamp": 1307386437,"volt": 2.5,"temp": 35.5,"acc": [[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3]],"sampletime":1307386437}
]

使用pandas读取json文件

import pandas as pd

fr = open('filename.json', 'r', encoding='utf-8')
json_info = fr.read()
df = pd.read_json(json_info)
df.to_csv('json_info.csv', index=False, columns=["mac", "timestamp", "volt", "temp", "acc", "sampletime"])
print(df)
print(df.mac)  # df['mac']  二者功能相同

输出

   mac  ...  sampletime
0    1  ...  1307386437
1    1  ...  1307386437

[2 rows x 6 columns]
0    1
1    1
Name: mac, dtype: int64

另有一点需注意:pandas直接读取格式化日期(比如:“datetime”: 2019-08-17 08:35:20)时会有问题,查了很多相关内容也没解决,在值两侧加引号可以解决,也可在写入时间时用时间戳。但我就是不想加也不想换,路过的大佬可否教我一手。

本文地址:https://blog.csdn.net/m0_46744629/article/details/110849872

相关标签: Python