如何将两列与应用于 pandas python 中的其中一列的条件相乘?

How to multiply two columns together with a condition applied to one of the columns in pandas python?

这是一些示例数据:

data = {'Company': ['A', 'B', 'C', 'D', 'E', 'F'],
        'Value': [18700, 26000, 44500, 32250, 15200, 36000],
        'Change': [0.012, -0.025, -0.055, 0.06, 0.035, -0.034]
       }
df = pd.DataFrame(data, columns = ['Company', 'Value', 'Change'])
df

Company Value   Change
0   A   18700   0.012
1   B   26000   -0.025
2   C   44500   -0.055
3   D   32250   0.060
4   E   15200   0.035
5   F   36000   -0.034

我想创建一个名为 'New Value' 的新专栏。此列的逻辑与每一行的以下内容类似:

我尝试使用以下循环创建一个列表并将其作为新列添加到 df,但当我预期只有 5 个(对应于 df 中的行数)时,返回的值比预期的多得多。

lst = []

for x in df['Change']:
    for y in df['Value']:
        if x > 0:
            lst.append(y + (y*x))
        elif x < 0:
            lst.append(y - (y*(abs(x))))
print(lst)

如果有人能指出我哪里做错了,或者建议替代方法,那就太好了:)

你的两个条件其实是一样的,所以这就是你需要做的:

df['New Value'] = df['Value'] + df['Value'] * df['Change']

输出:

>>> df
  Company  Value  Change  New Value
0       A  18700   0.012    18924.4
1       B  26000  -0.025    25350.0
2       C  44500  -0.055    42052.5
3       D  32250   0.060    34185.0
4       E  15200   0.035    15732.0
5       F  36000  -0.034    34776.0

或者,更简洁一点:

df['New Value'] = df['Value'] * df['Change'].add(1)

或者

df['New Value'] = df['Value'].mul(df['Change'].add(1))