首页 > 解决方案 > 从熊猫数据框创建一个json并发布到rest api

问题描述

我需要将数据发送到接受这种格式的 REST API

{'myattributes': 
 [{'a': {},
   'v': {},
   'c': {},
   'd': {},
   'e': {},
   'f': {},
   'g': {},
   'h': {}}]}

我正在从数据框中读取文件,如何将数据框映射到所需的 json 格式?

url = 'https://cyz.com/hello
response = requests.post(url, json=s, headers=head)
print(response)
print(response.json())

标签: jsondataframeapidictionary

解决方案


import pandas as pd

# grabbing a sample file to demonstrate
df = pd.read_csv("https://www1.ncdc.noaa.gov/pub/data/cdo/samples/PRECIP_HLY_sample_csv.csv") 

print(df)  # what it looks on read

# if the column names don’t match what’s needed for the api post json,rename them
df = df.rename(columns={'STATION':'a','STATION_NAME':'b',
                        'ELEVATION':'c','LATITUDE':'d',
                        'LONGITUDE':'e','DATE':'f','HPCP':'g',
                        'Measurement Flag':'h','Quality Flag':'i'})

print(df)  # what it looks like after the rename

# render a list of 'json' posts from the dataframe
posts = json.loads('{"items":' + df.to_json(orient='records', date_format='iso') + '}')

print(posts['items']) # see the results

# since posts['items'] is a list, the set of posts can be executed using list comprehension like line below
# [requests.post('http://someurl.com/path', json=post, headers={'Accept':'application/json'}) for post in posts['items'] ```

推荐阅读