2017-09-23 96 views
0

我有一個JSON文件,我想從中提取一些數據並將其導出爲CSV。我有兩個循環獲取我想要的數據,但似乎沒有任何工作將其導出到CSV文件,請幫助,我是一個noob!使用Python/Pandas將JSON導出爲CSV

這裏是我的代碼:

import csv 
    import json 
    from pandas.io.json import json_normalize 
    json_data = open('FuelCheckerV1.txt') 
    fueldata = json.load(json_data) 
    with open('out.csv') as csvfile: 
      csv = csv.writer(
       csvfile, 
       delimiter=',', 
       quotechar='"', 
       quoting=csv.QUOTE_MINIMAL 
     ) 
      csv.writerow(['code', 'name', 'address', 'stationcode', 'fueltype', 'price', 'lastupdated']) 
      for i in fueldata['stations']: 
       csv.writerow(i['code'], i['name'], i['address']) 
      for x in fueldata['prices']: 
       csv.writerow(x['stationcode'], x['fueltype'], x['price'], x['lastupdated']) 

這些都是爲得到我環路我想要的東西:

for i in fueldata['stations']: 
    print (i['code'], i['name'], i['address']) 

for x in fueldata['prices']: 
    print (x['stationcode'], x['fueltype'], x['price'], x['lastupdated']) 

回答

1

假設爲上述工作循環如預期,你可以嘗試創建一個列表的記錄,使用熊貓from_records方法創建數據幀,然後使用數據幀的to_csv方法。例如:

import pandas as pd 
import json 

fueldata = json.load(open('FuelCheckerV1.txt')) 

list_of_records = [ 
    (i['code'], 
    i['name'], 
    i['address'], 
    x['stationcode'], 
    x['fueltype'], 
    x['price'], 
    x['lastupdated'] 
    ) 
    for i, x in zip(fueldata['stations'], fueldata['prices']) 
] 

df = pd.DataFrame.from_records(
    list_of_records, 
    columns = ['code', 'name', 'address', 'stationcode', 'fueltype', 
       'price', 'lastupdated'] 
) 

df.to_csv('filename.csv') 

有可能還要創建從一個JSON數據幀的更直接的方法,但這應該工作只知道有關在您的例子循環。

+0

謝謝!這完美地工作,你已經做了我的一天! – Nigel78