首页 > 解决方案 > 如何将 pandas 行转换为自定义 json 格式并发出 POST 请求

问题描述

我的 DataFrame 包含以下列和行

hosp  doc   dep  p_t    ins   tpa       p_n  i_c  t_date       cat    c_amt

ALZ   Dr.M  Onc  SAICO  SAISA AZBRONZE  AZS  11   2020-08-11   Cons   341.25
ALZ   Dr.K  Card Mitra  Mit   ASGOLD    ASG  8265 2020-08-15   Cons   1123.45

我想将每一行转换为以下 json 格式并向 API 发出 post 请求。(请注意,“id”将始终为 1)

{
    "hosp": "ALZ",
    "doc": "Dr.M",
    "dep": "Onc",
    "p_t": "SAICO",
    "ins": "SAISA",
    "tpa": "AZBRONZE",
    "p_n": "AZS",
    "activities": [
        {
            "id": "1",
            "i_c": "11",
            "t_d": "2020-08-11",
            "cat": "Cons",
            "c_amt": "341.25"
        }
    ]
}

最后将响应作为新列添加到 DataFrame

hosp  doc   dep  p_t    ins   tpa       p_n  i_c  t_date       cat    c_amt    response

ALZ   Dr.M  Onc  SAICO  SAISA AZBRONZE  AZS  11   2020-08-11   Cons   341.25   Yes
ALZ   Dr.K  Card Mitra  Mit   ASGOLD    ASG  8265 2020-08-15   Cons   1123.45  No

标签: pythonpandasdataframerequest

解决方案


您可以应用 pandas 函数https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_json.htmldf.to_json()访问每一行以获取 json 演示文稿。


推荐阅读