【发布时间】:2021-06-24 16:13:33
【问题描述】:
我的脚本使用 pandas 从 Excel 文件中读取参数。
- 代码首先从一个 excel 文件中读取并创建一个
DataFrame、df。 -
df在df['Team'] == 'IT'上过滤。 - 过滤后的
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