错误 -> Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

Error -> The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

能否请您帮我整理一下以下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: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or 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 结尾且 bid > 0 添加 bid 值; 如果索引以 S 结尾并且 ask > 0 添加 ask 值; 如果这 2 个条件失败(即以 S 结尾但只有出价可用)如果出价 > 0 添加出价; 如果 mid > 0 添加 mid 值; 如果询问 > 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)