If statement 对熊猫使用If/Truth语句
我试着参考pandas文档,但仍然不知道如何继续 我有这些数据If statement 对熊猫使用If/Truth语句,if-statement,pandas,If Statement,Pandas,我试着参考pandas文档,但仍然不知道如何继续 我有这些数据 In [6]: df Out[6]: strike putCall 0 50 C 1 55 P 2 60 C 3 65 C 4 70 C 5 75 P 6 80 P 7 85 C 8 90 P 9
In [6]:
df
Out[6]:
strike putCall
0 50 C
1 55 P
2 60 C
3 65 C
4 70 C
5 75 P
6 80 P
7 85 C
8 90 P
9 95 C
10 100 C
11 105 P
12 110 P
13 115 C
14 120 P
15 125 C
16 130 C
17 135 P
18 140 C
19 145 C
20 150 C
我正在尝试运行以下代码:
if df['putCall'] == 'P':
if df['strike']<100:
df['optVol'] = 1
else:
df['optVol'] = -999
else:
if df['strike']>df['avg_syn']:
df['optVol'] = 1
else:
df['optVol']= =-999
上面的代码和数据只是为了说明我遇到的问题
任何协助都将不胜感激
约翰
OP附加组件
Joris很好地回答了上述问题,但我还有一个小小的补充问题
我如何调用函数,例如
def Bool2(df):
df['optVol'] = df['strike']/100
return(df)
而不是将optVol的值直接分配给行中的1:
df.loc[(df['putCall'] == 'P') & (df['strike']>=100), 'optVol'] = 1
我想调用Bool2函数并进行赋值。显然,Bool2函数比我描述的要复杂得多
我试过这个(在黑暗中拍摄),但没有成功:
df.loc[(df['putCall'] == 'P') & (df['strike']<100), 'optVol'] =df.apply(Bool2,axis=1)
df.loc[(df['putCall']='P')&(df['strike']通常,当您想要使用这种if-else逻辑设置值时,布尔索引是解决方案(请参阅):
逻辑是:
if df['strike']<100:
df['optVol'] = 1
上述代码的完整等价物可以如下所示:
df['optVol'] = -999
df.loc[(df['putCall'] == 'P') & (df['strike']>=100), 'optVol'] = 1
df.loc[(df['putCall'] != 'P') & (df['strike']>df['avg_syn']), 'optVol'] = 1
你得到上面错误信息的原因是因为当你做if df['strike']谢谢你Joris!做了这个把戏(并感谢你解释我为什么会出错)Joris,我在OP中添加了另一个请求,不确定你是否能帮上忙,最好把它作为一个新问题问
df.loc[df['strike'] < 100, 'optVol'] = 1
df.loc[(df['putCall'] == 'P') & (df['strike']>=100), 'optVol'] = 1
df['optVol'] = -999
df.loc[(df['putCall'] == 'P') & (df['strike']>=100), 'optVol'] = 1
df.loc[(df['putCall'] != 'P') & (df['strike']>df['avg_syn']), 'optVol'] = 1