如何基于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
相关产品推荐
相关产品推荐

