Pandas 不同的数学运算,以列值为条件

问题描述 投票:0回答:2
data= {'start_value':[10,20,30,40,50,60,70],
'identifier':['+','+','-','-','+','-','-']}
df = pd.DataFrame(data)
start_value identifier
0   10  +
1   20  +
2   30  -
3   40  -
4   50  +
5   60  -
6   70  -

我正在尝试创建一个新列“end_value”,它根据“identifier”列中的“+”或“-”值对 *“*start_value”列产生 +5 或 -5。导致下面的 df.

start_value identifier  end_value
0   10  +   15.0
1   20  +   25.0
2   30  -   25.0
3   40  -   35.0
4   50  +   55.0
5   60  -   55.0
6   70  -   65.0

运行这段代码我意识到替换了“end_value”列中的值,导致这个 df

df['end_value'] = 5 + df.loc[df['identifier']=="+"]['start_value']
df['end_value'] = -5 + df.loc[df['identifier']=="-"]['start_value']
start_value identifier  end_value
0   10  +   NaN
1   20  +   NaN
2   30  -   25.0
3   40  -   35.0
4   50  +   NaN
5   60  -   55.0
6   70  -   65.0

我将如何应用 if 语句来组合结果,如果标识符 col == "+" 则添加 5,如果标识符 col == "-" 则减去 5?

我已经使用下面这篇文章对字符串做了类似的事情,但我不确定如何成功地将其应用于数学运算,导致“end_value”dtype 为 float。

Pandas:如果A列中的行包含“x”,则将“y”写入B列中的行

python pandas dataframe calculated-columns
2个回答
1
投票

可以使用向量化操作:

import numpy as np

df['end_value'] = df['start_value'] + np.where(df['identifier'] == '+', 5, -5)

# OR

df['end_value'] = df['start_value'] + df['identifier'].replace({'+': 5, '-': 5})
print(df)

# Output
   start_value identifier  end_value
0           10          +         15
1           20          +         25
2           30          -         25
3           40          -         35
4           50          +         55
5           60          -         55
6           70          -         65

0
投票

您可以将

.apply()
与 lambda 表达式一起使用。

data= {'start_value':[10,20,30,40,50,60,70],
'identifier':['+','+','-','-','+','-','-']}
df = pd.DataFrame(data)
df["end_value"] = df.apply(lambda row: row.start_value + 5 if row.identifier == "+" else row.start_value - 5, axis=1)

假设标识符列的值是

+
-

© www.soinside.com 2019 - 2024. All rights reserved.