您能否帮我整理一下以下 if 条件:(也可以使用 apply 和 lambda,但不知道如何将这么多条件放在一行中)
test = pd.DataFrame({'index' : ['DS','VS','VB','FS','HB'],
'bid' : [np.nan,102,103,104,np.NaN],
'mid' : [106,107,108,109,110],
'ask' : [np.nan,112,113,114,115]})
print(test)
index bid mid ask
0 DS NaN 106 NaN
1 VS 102.0 107 112.0
2 VB 103.0 108 113.0
3 FS 104.0 109 114.0
4 HB NaN 110 115.0
我尝试了什么:
if (test['index'].str.endswith('B') and test['bid'] > 0).all():
test['fin'] == test['bid']
elif (test['index'].str.endswith('S')) and (test['ask'] > 0).all():
test['fin'] == test['ask']
elif test['bid'] > 0:
test['fin'] == test['bid']
elif test['mid'] > 0:
test['fin'] == test['mid']
else:
test['fin'] == test['ask']
仍然收到错误消息:
ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()
.预期输出:
index bid mid ask fin
0 DS NaN 106 NaN 106.0
1 VS 102.0 107 112.0 112.0
2 VB 103.0 108 113.0 103.0
3 FS 104.0 109 114.0 114.0
4 HB NaN 110 115.0 110.0 110 because no bid
解释:我想根据条件创建一个新的“fin”列:如果索引以 B 结尾并且出价 > 0 添加出价值;如果索引以 S 结尾并且询问 > 0 添加询问值;如果这 2 个条件失败(即以 S 结尾但只有出价可用)如果出价 > 0 添加出价值;如果 mid > 0 添加中间值;如果询问 > 0 添加询问值。
当您的条件非常复杂时,将条件编写在函数中并通过使用将其应用于每一行可能会更容易df.apply(func, axis=1)
import pandas as pd
import numpy as np
test = pd.DataFrame({'index' : ['DS','VS','VB','FS','HB'],
'bid' : [np.nan,102,103,104,np.NaN],
'mid' : [106,107,108,109,110],
'ask' : [np.nan,112,113,114,115]})
def extract_value(row):
if row['index'].endswith('B') and row['bid'] > 0:
return row['bid']
elif row['index'].endswith('S') and row['ask'] > 0:
return row['ask']
elif row['bid'] > 0:
return row['bid']
elif row['mid'] > 0:
return row['mid']
else:
return row['ask']
test['fin'] = test.apply(extract_value, axis=1)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句