Pandas 未根据条件填充列

Pandas not populating Column based on Condition

各位专家,

我遇到了 Pandas 的问题 ..

不确定为什么不满足以下条件。

df = pd.read_csv(path + filename, index_col='Date', parse_dates=True)
for i in range(1, len(signal)):

    if [(df['x'] < 2) & (df['y'] <= 0)]:
        listLongShort1.append("A_Condition")

# The other way around
    elif [(df['x'] > 3) & (df['y'] >= 1)]:
        listLongShort1.append("B_Condition")

    else:
        listLongShort1.append("No Condition")

它只是用 "A_Condition" 打印填充列,出于某种原因没有看到 elif 或其他。

你能告诉我我的代码有什么问题吗?

谢谢!!

python中的if条件是语句,所以用法是:

if expression-here :
    # your body

示例:

if (df['x'] < 2) and (df['y'] <= 0):
    # whatever you want to do.

根据您所做的,表达式位于列表 ([]) 中,它的值始终为 TrueFalse,因此列表中的表达式始终为一个布尔值,因此始终是一个元素的列表,它是 True in if condition of python.

即:

if [False]: # always true
    # always get's executed

if [True]: # always true
    # always get's executed

只有当列表为空时才会被传递为 false,即:

if []: # always false
    # doesn't get executed

但是由于在您的情况下这是不可能的,因此您总是面临 "truth" 的情况。

& 是位运算符。 AND 是您要用来检查条件的运算符。

if ((df['x'] < 2) and (df['y'] <= 0)):
    listLongShort1.append("A_Condition")
elif ((df['x'] > 3) and (df['y'] >= 1)):
    listLongShort1.append("B_Condition")
else:
    listLongShort1.append("No Condition")