使用Python/Pandas将JSON导出为CSV

问题描述:

我有一个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']) 

假设为上述工作循环如预期,你可以尝试创建一个列表的记录,使用熊猫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