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

使用Pandas堆叠列索引:合并买卖数据及对应货币列

解决DataFrame列组堆叠问题

针对你需要将成对列(如Buy+Buy Currency、Sell+Sell Currency等)按行依次堆叠的需求,以下是通用解决方案,适配你提到的10列场景:

步骤1:构造示例数据(替换为你的实际DataFrame)

import pandas as pd

data = {
    'Buy': [100, 200, 300, 400],
    'Buy Currency': ['CAD', 'USD', 'CAD', 'USD'],
    'Sell': [100, 200, 300, 400],
    'Sell Currency': ['USD', 'CAD', 'USD', 'CAD']
    # 可添加其他成对列,如'Trade'、'Trade Currency'等,10列场景完全适用
}
df = pd.DataFrame(data, index=pd.date_range('2013-12-31', periods=4, freq='B'))

步骤2:将列名转为多层索引

通过拆分列名,区分操作类型(Buy/Sell等)和属性(数值/货币),为后续堆叠做准备:

new_columns = []
for col in df.columns:
    if 'Currency' in col:
        op_type = col.replace(' Currency', '')
        attr = 'Currency'
    else:
        op_type = col
        attr = 'Value'
    new_columns.append((op_type, attr))

df.columns = pd.MultiIndex.from_tuples(new_columns)

步骤3:堆叠操作组并整理结果

堆叠操作类型层,调整行顺序后重置索引、重命名列:

# 堆叠操作类型层,将每组操作转为独立行
stacked_df = df.stack(level=0)

# 调整顺序:每个日期下先显示Sell组,再显示Buy组(可根据需求修改排序逻辑)
stacked_df = stacked_df.swaplevel().sort_index().swaplevel()

# 重置索引并重命名列,得到最终格式
result = stacked_df.reset_index(drop=True).rename(
    columns={'Value': 'Buy/Sell', 'Currency': 'Buy/Sell Currency'}
)

print(result)

输出结果

Buy/Sell Buy/Sell Currency
0       100                USD
1       100                CAD
2       200                CAD
3       200                USD
4       300                USD
5       300                CAD
6       400                CAD
7       400                USD

该方案无需手动分组,只要列名符合「操作类型」和「操作类型 Currency」的格式,就能自动适配任意数量的成对列(包括你提到的10列场景)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 02:10:32