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

如何为DataFrame所有行调用函数,基于timestamp生成price列?

问题

我有一个包含timestamp列的Pandas DataFrame,需要将每行的timestamp传入fetch_price函数获取对应价格,新增price列。DataFrame示例如下:

date_time   timestamp
0  2022-09-20 23:55:02  1663718102
1  2022-09-21 23:55:02  1663804502
2  2022-09-22 23:59:02  1663891142
3  2022-09-23 23:59:02  1663977542
4  2022-09-24 23:59:02  1664063942
5  2022-09-25 23:59:03  1664150343
6  2022-09-26 23:59:02  1664236742
7  2022-09-27 23:59:03  1664323143
8  2022-09-28 23:59:03  1664409543
9  2022-09-29 23:59:03  1664495943
10 2022-09-30 23:59:02  1664582342
11 2022-10-01 23:59:02  1664668742
12 2022-10-02 23:59:02  1664755142
13 2022-10-03 23:59:03  1664841543

使用的函数:

def fetch_price(timestamp):
    data = session_auth.query_kline(
        symbol="BTCUSDT",
        interval=1,
        limit=2,
        from_time=timestamp)
    price = data["result"][0]["close"]
    return price

目前能单独调用函数,但不知道如何结合DataFrame生成新列。

解决方案

1. 使用apply方法

直接对timestamp列应用函数,生成新列:

df['price'] = df['timestamp'].apply(fetch_price)

apply会遍历timestamp列的每个值,传入fetch_price后将返回结果组成price列。

2. 批量优化(推荐)

如果DataFrame行数多,逐个调用API效率低。若API支持批量查询,可一次性传入所有timestamp,再匹配结果:

# 获取所有timestamp
timestamps = df['timestamp'].tolist()

# 假设API支持批量请求(需根据实际API调整)
# data_batch = session_auth.query_kline_batch(symbol="BTCUSDT", interval=1, timestamps=timestamps)
# prices = [item['close'] for item in data_batch['result']]

# 若API不支持批量,用列表推导式(和apply效率接近,但便于添加异常处理)
prices = []
for ts in timestamps:
    try:
        prices.append(fetch_price(ts))
    except Exception as e:
        print(f"获取timestamp {ts}的价格失败: {e}")
        prices.append(None)

df['price'] = prices

异常处理建议

为避免单个请求失败导致整个流程中断,给fetch_price添加异常捕获:

def fetch_price(timestamp):
    try:
        data = session_auth.query_kline(
            symbol="BTCUSDT",
            interval=1,
            limit=2,
            from_time=timestamp)
        return data["result"][0]["close"]
    except (KeyError, ConnectionError) as e:
        print(f"获取timestamp {ts}的价格出错: {e}")
        return None

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:15:43