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

如何将方法获取的代币价格列添加至现有Exchange DataFrame?

批量为交易所代币DataFrame添加价格列解决方案

没问题,我来教你怎么搞定这个批量添加价格列的需求!咱们一步步来:

1. 先明确前提

首先得确认你的Exchange DataFrame里有一列存储了符合san模块要求的代币标识符(比如像例子里的huobi-token这种格式,可能你的列名叫slug或者symbol,下面代码里我用token_slug指代,你记得换成自己的列名哈)。

2. 定义批量获取价格的函数

先写一个可以获取单个代币价格的函数,还得处理获取失败的情况,避免整个程序崩掉:

import san

def get_token_price(token_slug, from_date="2018-06-01", to_date="2018-06-05"):
    try:
        # 调用san.get获取指定日期区间的价格数据
        price_df = san.get(f"prices/{token_slug}", from_date=from_date, to_date=to_date, interval="1d")
        # 这里可以根据你的需求返回价格:比如取最后一天的收盘价,或者区间均价
        # 示例里取最后一天的价格(假设返回的DataFrame里价格列叫'price')
        if not price_df.empty:
            return price_df.iloc[-1]["price"]
        else:
            # 如果没有返回数据,返回None(后续会显示为NaN)
            return None
    except Exception as e:
        # 捕获异常并打印,方便排查问题
        print(f"获取代币 {token_slug} 价格失败:{str(e)}")
        return None

3. 批量应用函数并添加新列

用apply方法把函数批量应用到每个代币的标识符上,然后把结果作为新列添加到Exchange DataFrame末尾:

# 先筛选出交易所代币(你已经写好的代码)
Exchange = df[df["marketSegment"] == "Exchange"]

# 批量生成价格列,替换成你实际的代币标识符列名(比如'token_slug')
Exchange["token_price"] = Exchange["token_slug"].apply(get_token_price)

# 如果需要自定义日期参数,可以用lambda传递:
# Exchange["token_price"] = Exchange["token_slug"].apply(lambda x: get_token_price(x, from_date="2018-06-01", to_date="2018-06-05"))

4. 优化提示(可选)

如果你的代币数量很多,apply可能有点慢,可以用swifter库来加速(需要先安装:pip install swifter):

import swifter

Exchange["token_price"] = Exchange["token_slug"].swifter.apply(get_token_price)

这样就能轻松批量给所有交易所代币添加上对应日期区间的价格啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:58:59