【问题标题】:How to combine the result of one HTTP call to update several cells?如何结合一次 HTTP 调用的结果来更新多个单元格?
【发布时间】:2022-12-13 23:05:28
【问题描述】:

我有一个 CSV 文件,其中有一列 id。我创建了一个新的 (m0),其内容来自以 id 作为参数的 HTTP 调用:

d['m0'] = d['id'].apply(lambda id: pd.read_json(f"http://localhost:3000/{id}").get('H', {}).get('M0', "X"))

我还需要以类似的方式创建列m1m2。我可以

d['m0'] = d['id'].apply(lambda id: pd.read_json(f"http://localhost:3000/{id}").get('H', {}).get('M0', "X"))
d['m1'] = d['id'].apply(lambda id: pd.read_json(f"http://localhost:3000/{id}").get('H', {}).get('M1', "X"))
d['m2'] = d['id'].apply(lambda id: pd.read_json(f"http://localhost:3000/{id}").get('H', {}).get('M2', "X"))

但是 HTTP 调用非常昂贵且缓慢(我有很多数据)。

有没有办法将所有三个调用合并为一个?,知道对于给定的id,我得到的 JSON 结构是

"H": {
  "M0": "sjkdhfjkshd",
  "M1": "isudfyfsdif",
  "M2": "azednbzaebe"
}

【问题讨论】:

    标签: pandas


    【解决方案1】:

    您可以编写一个通用函数,进行 HTTP 调用,提取所有必填字段并将结果作为 pandas Series 返回:

    def get_all_fields(row):
      h_json = pd.read_json(f"http://localhost:3000/{row['id']}").get('H', {})
      return pd.Series([
          h_json.get('M0', "X"),
          h_json.get('M1', "X"),
          h_json.get('M2', "X"),
      ])
    
    d[['m0', 'm1', 'm2']] = d.apply(lambda row: get_all_fields(row), axis=1)
    

    【讨论】:

      猜你喜欢
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      • 1970-01-01
      • 2016-07-04
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      相关资源
      最近更新 更多