I want to multiply two columns in a pandas DataFrame and add the result into a new column

前端 未结 7 1399
清酒与你
清酒与你 2020-12-02 09:49

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 co

7条回答
  •  自闭症患者
    2020-12-02 10:21

    I think an elegant solution is to use the where method (also see the API docs):

    In [37]: values = df.Prices * df.Amount
    
    In [38]: df['Values'] = values.where(df.Action == 'Sell', other=-values)
    
    In [39]: df
    Out[39]: 
       Prices  Amount Action  Values
    0       3      57   Sell     171
    1      89      42   Sell    3738
    2      45      70    Buy   -3150
    3       6      43   Sell     258
    4      60      47   Sell    2820
    5      19      16    Buy    -304
    6      56      89   Sell    4984
    7       3      28    Buy     -84
    8      56      69   Sell    3864
    9      90      49    Buy   -4410
    

    Further more this should be the fastest solution.

提交回复
热议问题