python dataframe两列相乘_我想将pandas DataFrame中的两列相乘并将结果添加到新列中...

在尝试将Pandas DataFrame中的'Prices'和'Amount'列相乘并根据'Action'列的值('Sell'或'Buy')决定乘以正负号时,遇到了错误。'Value'列的计算结果应考虑交易的方向,但所有数值均为正。解决方案是使用DataFrame的apply方法和lambda表达式创建表示交易方向的新列'C',然后根据'C'列的值进行乘法运算,正确计算'Value'列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I'm trying to multiply two existing columns in a pandas Dataframe (orders_df) - Prices (stock close price) and Amount (stock quantities) and add the calculation to a new column called 'Value'. For some reason when I run this code, all the rows under the 'Value' column are positive numbers, while some of the rows should be negative. Under the Action column in the DataFrame there are seven rows with the 'Sell' string and seven with the 'Buy' string.

for i in orders_df.Action:

if i == 'Sell':

orders_df['Value'] = orders_df.Prices*orders_df.Amount

elif i == 'Buy':

orders_df['Value'] = -orders_df.Prices*orders_df.Amount)

Please let me know what i'm doing wrong !

解决方案

If we're willing to sacrifice the succinctness of Hayden's solution, one could also do something like this:

In [22]: orders_df['C'] = orders_df.Action.apply(

lambda x: (1 if x == 'Sell' else -1))

In [23]: orders_df # New column C represents the sign of the transaction

Out[23]:

Prices Amount Action C

0 3 57 Sell 1

1 89 42 Sell 1

2 45 70 Buy -1

3 6 43 Sell 1

4 60 47 Sell 1

5 19 16 Buy -1

6 56 89 Sell 1

7 3 28 Buy -1

8 56 69 Sell 1

9 90 49 Buy -1

Now we have eliminated the need for the if statement. Using DataFrame.apply(), we also do away with the for loop. As Hayden noted, vectorized operations are always faster.

In [24]: orders_df['Value'] = orders_df.Prices * orders_df.Amount * orders_df.C

In [25]: orders_df # The resulting dataframe

Out[25]:

Prices Amount Action C Value

0 3 57 Sell 1 171

1 89 42 Sell 1 3738

2 45 70 Buy -1 -3150

3 6 43 Sell 1 258

4 60 47 Sell 1 2820

5 19 16 Buy -1 -304

6 56 89 Sell 1 4984

7 3 28 Buy -1 -84

8 56 69 Sell 1 3864

9 90 49 Buy -1 -4410

This solution takes two lines of code instead of one, but is a bit easier to read. I suspect that the computational costs are similar as well.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值