I am trying to import data from a csv file and format it appropriately to allow me to submit it as a POST request to an api. Here is my code. I'd like to be able to pull the data from my csv and have it replace the 'rows' portion of the data, so I'm not typing in thousands of lines, but I can't seem to get the formatting correct.
import pandas as pd
import json
df = pd.read_csv('test.csv', sep=',',header=0,parse_dates=True)
dfj = df.to_json(orient="records")
import requests
headers = {
'Authorization': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
}
data = {
'id': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
'rows':[
{ 'field_0': 123, 'field_1': 'Sup', 'field_2': 16.5 },
{ 'field_0': 321, 'field_1': 'Nice', 'field_2': 16.2 },
{ 'field_0': xyz, 'field_1': 'Apple', 'field_2': 16.1 },
{ 'field_0': dfd, 'field_1': 'Orange', 'field_2': 19.2 }
]
}
response = requests.post('https://www.api.com/upload/data',
headers=headers,
json=data)
I'm sure I am overlooking something simple, but maybe I am going about this the wrong way.
答案 0 :(得分:0)
我知道我迟早会搞清楚。使用标准的csv阅读器,我只需要格式化为字典列表。
import csv
with open('test.csv', 'rb') as f:
reader = csv.DictReader(f)
your_list = list(reader)
现在数据的格式正确,可用于API导入。