簡體   English   中英

如何從json文件中讀取數據,並使用熊貓將其轉換為csv?

[英]How to read data from json file and convert it to csv using pandas?

我正在做一個數據挖掘項目。 我需要從屬於亞馬遜的json格式數據集中讀取數據。
數據集的格式如下:
Json格式的數據集 首先,我要提取這些行:
[productName],[rating]
之后,我想將行寫入具有兩個列分別為productName和Rating的csv文件中。 有什么方法可以使用pandas庫來實現嗎?

有了一部分數據,我已經將其轉換為DF。請注意,您擁有的數據不是json格式的數據。

import pandas as pd
import json 
from collections import defaultdict
import re

f=open('inv.json')
text= f.readlines()
RowID=[]
result={}

for item in text:
    if item.startswith("###"):
        RowID=re.findall('\d+', item)
        result[RowID[0]]={}
    elif ":" in item:
        key,value =item.split(":",1)
        result[RowID[0]][key.strip()]=value.strip()
df= pd.DataFrame(result)
print df.transpose()

樣本輸入

    #####1
[ID]:0
[ProductId]:0
[rating]:2.0

#####2
[ID]:1
[ProductId]:2
[rating]:3.0
[fullText]:It is a good
[weburl]:http://example.org:xx

輸出

       [ID] [ProductId]    [fullText] [rating]           [weburl]
1    0           0           NaN      2.0                NaN
2    1           2  It is a good      3.0  http://example.org:xx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM