我是一个JSon文档,我想将其转换为Excel或CSV。我的JSON文件如下所示:
df = pd.DataFrame(columns=[Store,Address,User,Rating], dtype='unicode')
以下数据:
Store | Address | User | Rating
|:----------------------------------------:|
Store X| Adresse X | User 1 | 3
| | User 2 | 5
| | User 3 | 2
Store Y| Adresse Y | User 1 | 2
| | User 2 | 1
| | User 3 | 4
| | User 4 | 5
我尝试使用Code将Json Doc转换为Excel:
jsonDoc = pd.read_json(df.to_json())
ExcelDoc = jsonDoc.to_excel("C:\Users\output.xlsx")
但我得到以下输出:
Store | Address | User | Rating
|:-------------------------------------------------------:|
Store X| Adresse X | User 1,User2,User3 | 3,5,2
Store Y| Adresse Y | User 1,User2,User3,User4 | 2,1,4,5
但我希望我的excel文件是这样的:
Store | Address | User | Rating
|:----------------------------------------:|
Store X| Adresse X | User 1 | 3
Store X| Adresse X | User 2 | 5
Store X| Adresse X | User 3 | 2
Store Y| Adresse Y | User 1 | 2
Store Y| Adresse Y | User 2 | 1
Store Y| Adresse Y | User 3 | 4
Store Y| Adresse Y | User 4 | 5
有人能帮助我吗?我该如何实现呢?是否有可以处理它的库?
答案 0 :(得分:1)
我只做了一个月,但我主要不得不和.json和.xlsx一起工作,因为这主要是我需要python的。
我使用和喜欢的主要是Tablib。当我需要更多使用excel的功能时,我使用Openpyxl。
http://docs.python-tablib.org/en/master/api/
data = tablib.Dataset(headers=('Store', 'Address', 'User', 'Rating'))
有几种方法可以将数据导入tablib,我更喜欢以下方法,因为它也适用于数据手册(多个数据集)。
import tablib
import_filename = 'jsondatafile.json'
data.json = open(import_filename, 'r').read()
将其转换为xlsx或csv:
print(data.xlsx)
print(data.csv)
将其写入文件:
data_export = data.export('xlsx')
with open('C:/file.xlsx', 'wb') as f: # open the xlsx file
f.write(data_export) # write the dataset to the xlsx file
f.close()
Tablib可以做的很棒,查看他们的API或获取快速入门指南。