【问题标题】:Most efficient way to update Dataframe with JSON array from WebService使用 WebService 中的 JSON 数组更新 Dataframe 的最有效方法
【发布时间】:2019-04-11 14:38:11
【问题描述】:

我有一个 code 列,我想将其传递给 Web 服务并使用返回的 JSON 中的两个值(RbcSecurityDescriptionRbcSecurityType1 ). 我已经通过迭代实现了这一点,但我想知道是否有更有效的方法来做到这一点?

# http://postgre01:5002/bond/912828XU9

import requests
url = 'http://postgre01:5002/bond/'

def fastquery(code):
    response = requests.get(url + code)
    return response.json()

这是示例返回调用:

这里是dfMRD1['Cache_Ticker']dfMRD1['Cache_Product']的更新

dfMRD1 = df[['code']].drop_duplicates()
dfMRD1['Cache_Ticker'] = ""
dfMRD1['Cache_Product'] = ""
for index, row in dfMRD1.iterrows():
    result = fastquery(row['code'])
    row['Cache_Ticker'] = result['RbcSecurityDescription']        
    row['Cache_Product'] = result['RbcSecurityType1']          
display(dfMRD1.head(5))

最好只返回 json 数组,取消它并将其内容中的所有字段转储到另一个我可以与 dfMRD1 加入的 df 吗?实现这一目标的最佳方法?

【问题讨论】:

    标签: python arrays json pandas


    【解决方案1】:

    代码中最耗时的部分可能是发出同步请求。相反,您可以利用 requests-futures 发出异步请求,将列构造为结果列表并分配回 DF。我们没有什么要测试的,但方法看起来像这样:

    from requests_futures.sessions import FuturesSession
    
    session = FuturesSession(max_workers = 10)
    codes = df[['code']].drop_duplicates().values.tolist() # Take out of DF
    url = 'http://postgre01:5002/bond/'
    
    fire_requests = [session.get(url + code) for code in codes] # Async requests
    responses = [item.result() for item in fire_requests] # Grab the results
    
    dfMRD1['Cache_Ticker'] = [result['RbcSecurityDescription']
                              for result in responses]
    dfMRD1['Cache_Product'] = [result['RbcSecurityType1']
                               for result in responses] 
    

    根据 DF 的大小,您可能会在内存中获得大量数据。如果这成为问题,您将需要 background callback 在 JSON 响应返回时对其进行修剪。

    【讨论】:

    • 嘿@roganjosh,收到错误 ModuleNotFoundError: No module named 'requests_futures'
    • @PeterLucas 它不是标准库的一部分,你需要install it
    • 啊好吧!!立即安装,检查
    猜你喜欢
    • 2019-01-30
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 2023-02-24
    • 2023-02-23
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    相关资源
    最近更新 更多