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

如何基于DataFrame中Put/Call列的值迁移数据并整理输出

解决方案

原始DataFrame结构如下:

Put/Call StrikePrice fixedprice floatprice fixedspread floatspread
Put          10           0         20           0           0
Put          10           0         20           0           0
nan           0           0          0           13          15
nan           0           0          0           14          16

用Pandas即可完成数据迁移与列删除操作,代码如下:

import pandas as pd

# 构造原始DataFrame
data = {
    'Put/Call': ['Put', 'Put', None, None],
    'StrikePrice': [10, 10, 0, 0],
    'fixedprice': [0, 0, 0, 0],
    'floatprice': [20, 20, 0, 0],
    'fixedspread': [0, 0, 13, 14],
    'floatspread': [0, 0, 15, 16]
}
df = pd.DataFrame(data)

# 迁移Put行的数据:StrikePrice→fixedspread,floatprice→floatspread
df.loc[df['Put/Call'] == 'Put', 'fixedspread'] = df['StrikePrice']
df.loc[df['Put/Call'] == 'Put', 'floatspread'] = df['floatprice']

# 删除不需要的列
df = df.drop(columns=['Put/Call', 'StrikePrice', 'floatprice', 'fixedprice'])

print(df)

执行后输出结果:

fixedspread  floatspread
0           10           20
1           10           20
2           13           15
3           14           16

逻辑说明

  • 通过df.loc精准定位Put/Call为Put的行,直接覆盖目标列的值;
  • 用drop(columns=...)批量删除冗余列,快速得到目标结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:32:04