使用python将单列csv转换为多列csv?

时间:2019-12-30 09:30:12

标签: python json pandas csv

我在下面给出的代码会将API响应转换为CSV文件,但将API的整个响应都转储到了一次列中,但是我需要在不同的列中添加标头 'SKU','Category_name','price','specialPrice','size','offers'

  
    
      
        

里面的数据是对象,对象,float64,float64,对象(这是我们不得不提到的大小,东西是它的列表),对象,         整个东西都在列表中

      
    
  
import requests
import json
import time
import datetime
from datetime import datetime

my_data = {
"category_ids" : "948",
"limit" : "10000"
}

my_headers = {
  'Content-Type': 'application/json'
}

response = requests.post('https://newapi.zivame.com/api/v1/catalog/list', data=json.dumps(my_data),
                     headers=my_headers)


data = response.json()
products = data.get("data").get("docs")
x=products.get(0)
dataList = []



for product in products:
    valuepack = product.get("valuePackOffers",None)
    offer = []
    if valuepack:
        for v in valuepack:
            offer.append(v.get("display_name",None))
    #ts = datetime.now().timestamp()
    #datatime_data = datetime.fromtimestamp(ts)


    dataList.append([product.get("sku",None), product.get("mainCategoryName",None), product["price"], product["specialPrice"], product.get("sizes",None), offer])

len(dataList)




with open(r'/home/arcod/Downloads/data.json','w') as js:
    json.dump(dataList, js)


#import pandas
#from pandas.io.json import json_normalize
#data1 = json.load('/home/arcod/Downloads/data.json')
#norm_data = pd.DataFrame(json_normalize(data1))
#import os
#os.open(r'/home/arcod/Downloads/test.csv','w')
#norm_data.to_csv('/home/arcod/Downloads/test.csv')

import csv

with open(r'/home/arcod/Downloads/promos_zivame.csv','w') as csvFile:
    writer = csv.writer(csvFile)
    writer.writerows(dataList)


import pandas as pd

dl = pd.read_csv('/home/arcod/Downloads/promos_zivame.csv','wb', delimiter=",", error_bad_lines=False)
dl.dtypes
print(dl.dtypes)
new_dl = pd.DataFrame()

index = 1
for i in range(0, len(dl)):
    new_dl['' + str(index)] = dl[0].iloc[i:i+10].reset_index(drop=True)
    index +=1

print(new_dl)



print('Done')

2 个答案:

答案 0 :(得分:1)

csv编写功能的变化

import csv

with open(r'/home/arcod/Downloads/promos_zivame.csv','w') as csvFile:
    writer = csv.writer(csvFile)
    writer.writerow(('SKU', 'Category_name', 'price', 'specialPrice', 'sizes', 'offers'))
    writer.writerows(dataList)

答案 1 :(得分:0)

而不是将dataList另存为json,为什么不能将其另存为csv文件。

import pandas as pd
dl = pd.DataFrame(dataList, columns = ['SKU', 'Category_name', 'price', 'specialPrice', 'sizes', 'offers'])
dl.to_csv('/home/arcod/Downloads/promos_zivame.csv')