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

Pandas合并比特币数据与交易历史:交易类型标记问题求助

解决Pandas合并比特币行情与交易数据并标记交易类型的问题

核心思路

不要先拼接所有数据再标记类型,而是先给每个数据源单独打上交易类型标签,再合并,这样能精准区分各行的来源。

步骤详解

假设你的样本数据结构如下:

import pandas as pd

# 比特币分钟行情数据(每分钟0秒)
bitcoin_df = pd.DataFrame({
    'timestamp': pd.to_datetime(['2024-01-01 00:00:00', '2024-01-01 00:01:00', '2024-01-01 00:02:00']),
    'price': [45000, 45100, 44900]
})

# 买入交易数据(精确到秒)
buys = pd.DataFrame({
    'timestamp': pd.to_datetime(['2024-01-01 00:00:30', '2024-01-01 00:01:15']),
    'amount': [0.5, 0.2]
})

# 卖出交易数据(精确到秒)
sells = pd.DataFrame({
    'timestamp': pd.to_datetime(['2024-01-01 00:01:45']),
    'amount': [0.3]
})

1. 给各数据源打标签

直接在每个数据框中添加transaction_type列:

# 行情数据留空
bitcoin_df['transaction_type'] = ''
# 买入数据标记为"buy"
buys['transaction_type'] = 'buy'
# 卖出数据标记为"sell"
sells['transaction_type'] = 'sell'

2. 合并并排序数据

用pd.concat合并所有数据,再按时间戳排序:

# 合并所有数据,重置索引
combined_df = pd.concat([bitcoin_df, buys, sells], ignore_index=True)
# 按时间戳排序,保证时序正确
combined_df = combined_df.sort_values('timestamp').reset_index(drop=True)

3. (可选)将交易数据匹配到对应分钟行情

如果需要让交易数据关联到其所在分钟的行情价格,可以用merge_asof(需确保数据已按时间排序):

# 先对所有数据按时间戳排序
bitcoin_df_sorted = bitcoin_df.sort_values('timestamp')
buys_sorted = buys.sort_values('timestamp')
sells_sorted = sells.sort_values('timestamp')

# 将买入交易匹配到最近的前一分钟行情
merged_buys = pd.merge_asof(buys_sorted, bitcoin_df_sorted, on='timestamp', direction='backward')
# 将卖出交易匹配到最近的前一分钟行情
merged_sells = pd.merge_asof(sells_sorted, bitcoin_df_sorted, on='timestamp', direction='backward')

# 合并行情与匹配后的交易数据
final_df = pd.concat([bitcoin_df, merged_buys, merged_sells], ignore_index=True)
final_df = final_df.sort_values('timestamp').reset_index(drop=True)

为什么之前的代码会出错?

之前先拼接再标记的方式(比如用isin)无法精准判断行的来源——因为不同数据框可能存在重复值,isin是逐值匹配而非整行匹配,导致标签标记混乱。提前给每个数据源打标签是最可靠的方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 09:35:24