如何基于布尔逻辑修改Pandas DataFrame的strike列值为季度行权价
转换Pandas DataFrame的Strike列为季度行权价
没问题,我来帮你实现这个需求。这里有两种高效的方法来处理你的DataFrame,按照你指定的规则转换strike列:
方法1:使用Pandas的apply函数
这种方法代码直观,适合快速实现:
import pandas as pd # 构建你的原始DataFrame data = { 'code': ['CBT_21_G2015_S']*6, 'date': ['2015-01-02']*6, 'type': ['C', 'P', 'C', 'P', 'P', 'C'], 'strike': [126.2, 131.7, 102.5, 110.5, 101.2, 140.5], 'settlement': [1.343750, 4.359375, 24.671875, 0.015625, 0.015625, 0.015625] } df = pd.DataFrame(data) # 应用规则:若strike不能被0.25整除,则加0.05 df['strike'] = df['strike'].apply(lambda x: x + 0.05 if x % 0.25 != 0 else x)
方法2:使用Numpy的向量化操作(推荐大数据量场景)
向量化操作比apply效率更高,适合处理大规模数据集:
import pandas as pd import numpy as np # 同样先构建原始DataFrame data = { 'code': ['CBT_21_G2015_S']*6, 'date': ['2015-01-02']*6, 'type': ['C', 'P', 'C', 'P', 'P', 'C'], 'strike': [126.2, 131.7, 102.5, 110.5, 101.2, 140.5], 'settlement': [1.343750, 4.359375, 24.671875, 0.015625, 0.015625, 0.015625] } df = pd.DataFrame(data) # 向量化处理规则 df['strike'] = np.where(df['strike'] % 0.25 != 0, df['strike'] + 0.05, df['strike'])
修改后的结果
处理完成后,你的DataFrame会变成这样:
| code | date | type | strike | settlement | |
|---|---|---|---|---|---|
| 0 | CBT_21_G2015_S | 2015-01-02 | C | 126.25 | 1.343750 |
| 1 | CBT_21_G2015_S | 2015-01-02 | P | 131.75 | 4.359375 |
| 2 | CBT_21_G2015_S | 2015-01-02 | C | 102.50 | 24.671875 |
| 3 | CBT_21_G2015_S | 2015-01-02 | P | 110.50 | 0.015625 |
| 4 | CBT_21_G2015_S | 2015-01-02 | P | 101.25 | 0.015625 |
| 5 | CBT_21_G2015_S | 2015-01-02 | C | 140.50 | 0.015625 |
可以看到,所有不符合季度行权价规则的strike值都被调整为0.25的倍数了,完全符合你的要求。
内容的提问来源于stack exchange,提问作者steff
相关产品推荐
相关产品推荐

