Python 有效地将流数据添加到数据帧

Python 有效地将流数据添加到数据帧,python,json,python-3.x,pandas,Python,Json,Python 3.x,Pandas,我有一个连接到一个API的接口,我从该接口传输数据 看起来是这样的: #An example line of the output from the API: {'tick': {'instrument': 'AUD_USD', 'bid': 0.74692 , 'time': '2015-07-09T07:42:48.127521Z', 'ask': 0.74709}} 我将其放入一个数据框中进行如下处理: df = pd.DataFrame(columns=('time','bid','a

我有一个连接到一个API的接口,我从该接口传输数据 看起来是这样的:

#An example line of the output from the API:
{'tick': {'instrument': 'AUD_USD', 'bid': 0.74692
, 'time': '2015-07-09T07:42:48.127521Z', 'ask': 0.74709}}
我将其放入一个数据框中进行如下处理:

df = pd.DataFrame(columns=('time','bid','ask')) 
for line in response.iter_lines(1):             
     if line:
        try:
            msg = json.loads(line.decode())     
            if "instrument" in msg or "tick" in msg: 
                x  = pd.DataFrame([[msg['tick']['time'],msg['tick']['bid'],msg['tick']['ask']]], columns=('time','bid','ask'))
                df = df.append(x, ignore_index=True) 
        except Exception as e:
            print("Caught exception when converting message into json\n" + str(e))
我的问题是,有没有更有效的方法将数据导入 数据帧是否比上面的数据帧更大?然而,如果有一种完全不同的方式来做这件事,那么请一定要启发我

我特别怀疑这句话:

x  = pd.DataFrame([[msg['tick']['time'],msg['tick']['bid'],msg['tick']['ask']]], columns=('time','bid','ask'))
正如我想象的那样,获取字典信息可能更有效


谢谢你的帮助,我真的很感激

您不需要将dict强制转换为数据帧来追加,您可以将字典直接传递到
append
,如下所示:

df = df.append(msg['tick'],ignore_index=True)
如果您想在一批中加载它们,您可以使用列表理解来清理响应,只保留具有正确键的条目,然后将其传递到
append
(但您将无法跳过个别异常)


嘿,谢谢,很高兴知道我可以直接追加-虽然我怎么做而不从msg带回所有字段?因为我想从dataframeah中排除'instrument'字段,所以我没有注意到它正在添加另一列!我已经更新了我的答案,只需在列表中选择你想要的列。这明显提高了流速度,谢谢堆!
response_cleaned = [{'time': msg['tick']['time'],
                     'bid': msg['tick']['bid'],
                     'ask': msg['tick']['ask']} 
               for msg in response 
               if 'tick' in msg 
               and 'ask' in msg['tick'] 
               and 'time' in msg['tick'] 
               and 'bid' in msg['tick']]

print("{} bad records recieved".format(len(response) - len(response_cleaned)))

df = df.append(response_cleaned)