Skip to main content
 首页 » 编程设计

python之基于其他 2 列 python pandas 乘以 df 的 2 个子集

2024年10月17日5lidabo

我有一个 df 这样的有:

df 
Out[177]:  
              IV  maturity  strike 
date                               
2000-12-29 0.435     0.083   0.600 
2000-12-29 0.390     0.083   0.700 
2000-12-29 0.331     0.083   0.800 
2000-12-29 0.283     0.083   0.900 
2000-12-29 0.391     0.250   0.600 
2000-12-29 0.349     0.250   0.700 
2000-12-29 0.304     0.250   0.800 
2000-12-29 0.268     0.250   0.900 

我正在尝试创建 4 个新行,其中 maturity = 0 并且 IV 等于 IV 的乘积,其中 maturity==0.083 IV 和 maturity==0.25 IV 和'strike'匹配在一起(例如:IV for strike 0.6 和到期日 0.083 是 0.435 和 IV 到期日 0.25 行使价 0.6 us 0.391,所以 0.391*0.435

 Out[177]:  
                  IV  maturity  strike 
    date                               
    2000-12-29 0.435     0.083   0.600 
    2000-12-29 0.390     0.083   0.700 
    2000-12-29 0.331     0.083   0.800 
    2000-12-29 0.283     0.083   0.900 
    2000-12-29 0.391     0.250   0.600 
    2000-12-29 0.349     0.250   0.700 
    2000-12-29 0.304     0.250   0.800 
    2000-12-29 0.268     0.250   0.900 
    2000-12-29 0.170     0.000   0.600 
    2000-12-29 0.136     0.000   0.700 
    2000-12-29 0.101     0.000   0.800 
    2000-12-29 0.758     0.000   0.900 

谢谢你的帮助!

请您参考如下方法:

您可以使用 pivot ,然后由 iloc 选择的多个第一列和第二列到新列 0。最后 unstack与 reset_index :

df1 = (df.pivot(index='strike', columns='maturity', values='IV')) 
 
df1.loc[:,0] = df1.iloc[:,0] * df1.iloc[:,1] 
 
print (df1.unstack().reset_index(name='IV')) 
    maturity  strike        IV 
0      0.083     0.6  0.435000 
1      0.083     0.7  0.390000 
2      0.083     0.8  0.331000 
3      0.083     0.9  0.283000 
4      0.250     0.6  0.391000 
5      0.250     0.7  0.349000 
6      0.250     0.8  0.304000 
7      0.250     0.9  0.268000 
8      0.000     0.6  0.170085 
9      0.000     0.7  0.136110 
10     0.000     0.8  0.100624 
11     0.000     0.9  0.075844