You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决polygon.io WebSocket场景下pandas.append弃用转concat的报错问题

解决Polygon WebSocket客户端中pd.concat替代append的报错问题

问题核心:df.append()能自动将CryptoTrade对象列表转换为DataFrame行,但pd.concat()要求输入必须是DataFrame/Series类型,直接传原始对象列表会触发类型错误。

修复步骤

  1. 将每个CryptoTrade对象转换为字典(Polygon的模型类自带to_dict()方法)
  2. 把字典列表转为临时DataFrame
  3. 用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()方法返回的字段太多,你可以手动指定需要的字段,比如:
    temp_df = pd.DataFrame([{
        'timestamp': msg.timestamp,
        'price': msg.price,
        'size': msg.size,
        'symbol': msg.symbol
    } for msg in msgs])
    
    这样能生成更精简的DataFrame,避免不必要的字段。

内容的提问来源于stack exchange,提问作者morgan4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 00:05:46