如何解决polygon.io WebSocket场景下pandas.append弃用转concat的报错问题
解决Polygon WebSocket客户端中pd.concat替代append的报错问题
问题核心:df.append()能自动将CryptoTrade对象列表转换为DataFrame行,但pd.concat()要求输入必须是DataFrame/Series类型,直接传原始对象列表会触发类型错误。
修复步骤
- 将每个
CryptoTrade对象转换为字典(Polygon的模型类自带to_dict()方法) - 把字典列表转为临时DataFrame
- 用
pd.concat()合并原DataFrame和临时DataFrame
修改后的代码
import pandas as pd from polygon.websocket import WebSocketClient from polygon.websocket.models import WebSocketMessage from typing import List df = pd.DataFrame() c = WebSocketClient(api_key='APIKEYHERE', feed='socket.polygon.io', market='crypto', subscriptions=["XT.BTC-USD"]) def handle_msg(msgs: List[WebSocketMessage]): global df # 将每个消息对象转为字典,再生成临时DataFrame temp_df = pd.DataFrame([msg.to_dict() for msg in msgs]) # 合并原DataFrame和临时DataFrame df = pd.concat([df, temp_df], ignore_index=True) print(df) c.run(handle_msg)
关键说明
- 如果
to_dict()方法返回的字段太多,你可以手动指定需要的字段,比如:
这样能生成更精简的DataFrame,避免不必要的字段。temp_df = pd.DataFrame([{ 'timestamp': msg.timestamp, 'price': msg.price, 'size': msg.size, 'symbol': msg.symbol } for msg in msgs])
内容的提问来源于stack exchange,提问作者morgan4
相关产品推荐
相关产品推荐

