【问题标题】:How to convert Python JSON to API call string from dataframe如何将 Python JSON 从数据帧转换为 API 调用字符串
【发布时间】:2021-06-24 16:13:33
【问题描述】:

我的脚本使用 pandas 从 Excel 文件中读取参数。

  1. 代码首先从一个 excel 文件中读取并创建一个DataFramedf
  2. dfdf['Team'] == 'IT' 上过滤。
  3. 过滤后的df 转换为 JSON 以获取所有参数和值。

这是代码:

import pandas as pd
import json

loc = "excel.xlsx"
df = pd.read_excel(loc)

# "Team" is filtered by 'IT'
rslt_df = df[df["Team"] == 'IT'] 

# Encoding a DataFrame using "columns" formatted JSON
result = rslt_df.to_json(orient="columns")

# Parse json results
parsed = json.loads(result)

df 输出使用"IT" 过滤"Team"

   StartDate    EndDate startTime   endTime      Team   RotationID     Users
0 2021-04-01 2021-04-02  17:00:00  01:00:00      IT     081435f       john@dotdansh.io
2 2021-04-02 2021-04-03  17:00:00  01:00:00      IT     081435f       paul@dotdansh.io
4 2021-04-03 2021-04-04  17:00:00  01:00:00      IT     081435f       danny@dotdansh.io
6 2021-04-04 2021-04-05  17:00:00  01:00:00      IT     081435f       ben@dotdansh.io

使用 'columns' 数据结构过滤的 df 的 JSON 输出:

{
    "StartDate": {"0": "2021-04-01", "2": "2021-04-02", "4": "2021-04-03", "6": "2021-04-04"},
    "EndDate": {"0": "2021-04-02", "2": "2021-04-03", "4": "2021-04-04", "6": "2021-04-05"},
    "startTime": {"0": "17:00:00", "2": "17:00:00", "4": "17:00:00", "6": "17:00:00"},
    "endTime": {"0": "01:00:00", "2": "01:00:00", "4": "01:00:00", "6": "01:00:00"},
    "Team": {"0": "IT", "2": "IT", "4": "IT", "6": "IT"},
    "RotationID": {"0": "081435f", "2": "081435f", "4": "081435f", "6": "081435f"},
    "User": {"0": "john@dotdansh.io", "2": "paul@dotdansh.io", "4": "danny@dotdansh.io", "6": "ben@dotdansh.io"}
}

我需要使用从下面的 JSON 接收的参数创建一个 API PATCH 请求。 请注意,值可以不同,值的计数也可以不同。

这是API补丁调用的数据字符串,需要的参数:

import requests

headers = {
    'Authorization': 'Key <myKey>',
    'Content-Type': 'application/json',
}
data = ' { "name": "<Team>", "startDate": "<first_startDate>T<first_startTime>Z", "endDate": "<last_endDate>T<last_endTime>Z",\
 "type": "daily", "length": 1,\
 "participants": [\.    ##list of users
 { "type": "user",\
      "username": "john@dotdansh.io" },\
 { "type": "user",\
      "username": "paul@dotdansh.io"}\
 ] } }'
response = requests.patch('https://example.com', headers=headers, data=data)

【问题讨论】:

  • 我更新了你的问题。请记住,排序只是订购一些东西。元素的数量不会改变。您所做的称为过滤,过滤的目的是删除元素,而不是重新排序。

标签: python json python-3.x pandas python-requests


【解决方案1】:

我建议使用 groupby 将用户集中在一起,然后定位 'records' 而不是 'columns'

df = df.groupby(['Team', 'StartDate', 'EndDate', 'RotationID']).agg(tuple).reset_index()

for record in df.to_dict(orient='records'):
    payload = {
        "name": record['Team'],
        "startDate": record['StartDate'],
        "endDate": record['EndDate'],
        "rotationid": record['RotationID'],
        "participants": [{ "type": "user", "username": user } for user in record['User']]
    }
    requests.patch('https://example.com/endpoint', data=payload)

groupby() 创建一个可以运行聚合的对象,例如sum()mean()。但在这种情况下,我们想要所有结果,所以我们使用tuple 构造函数“聚合”。这意味着用户最终会在每个组中使用tuple。因为 groupby 将您分组的内容添加到索引中,所以我在末尾删除了索引,以便 to_dict() 函数也返回它们。您的示例数据在一个组中没有多个用户,因此我在运行中添加并获得了以下有效负载:

{'name': 'IT', 'startDate': '2021-04-01', 'endDate': '2021-04-02', 'rotationid': '081435f', 'participants': [{'type': 'user', 'username': 'john@dotdansh.io'}]}
{'name': 'IT', 'startDate': '2021-04-02', 'endDate': '2021-04-03', 'rotationid': '081435f', 'participants': [{'type': 'user', 'username': 'paul@dotdansh.io'}]}
{'name': 'IT', 'startDate': '2021-04-03', 'endDate': '2021-04-04', 'rotationid': '081435f', 'participants': [{'type': 'user', 'username': 'danny@dotdansh.io'}]}
{'name': 'IT', 'startDate': '2021-04-04', 'endDate': '2021-04-05', 'rotationid': '081435f', 'participants': [{'type': 'user', 'username': 'ben@dotdansh.io'}, {'type': 'user', 'username': 'other@dotdansh.io'}]}

【讨论】:

  • 感谢您的回答 Andrew,如果我没记错的话,您的代码将根据现有记录创建 PATCH 请求,我想用第一个 startDate startTime 和最后一个 endDate endTimeusers 的列表就像你提到的那样。 Team 需要过滤,因为 Excel 文件中有几条 Team 记录,我需要为每个 Team 发出一个 API 请求。
  • 我在我的问题中更新了我的 API PATCH 请求。
  • 嘿安德烈,你有机会看看我的评论吗?
猜你喜欢
  • 2023-03-31
  • 1970-01-01
  • 2020-09-06
  • 1970-01-01
  • 2021-12-18
  • 2023-03-16
  • 1970-01-01
  • 2021-12-10
  • 2015-02-19
相关资源
最近更新 更多