【问题标题】:create a json from pandas dataframe AND post to rest api从熊猫数据框创建一个json并发布到rest api
【发布时间】:2021-07-28 21:53:58
【问题描述】:

我需要将数据发送到接受这种格式的 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())

【问题讨论】:

标签: json dataframe api dictionary


【解决方案1】:
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'] ```

【讨论】:

    猜你喜欢
    • 2022-09-24
    • 1970-01-01
    • 2013-09-25
    • 2015-03-28
    • 2021-04-10
    • 2019-04-18
    • 1970-01-01
    • 2021-11-11
    • 2019-11-12
    相关资源
    最近更新 更多