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

前端 未结 7 1314
清酒与你
清酒与你 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:28

    For me, this is the clearest and most intuitive:

    values = []
    for action in ['Sell','Buy']:
        amounts = orders_df['Amounts'][orders_df['Action'==action]].values
        if action == 'Sell':
            prices = orders_df['Prices'][orders_df['Action'==action]].values
        else:
            prices = -1*orders_df['Prices'][orders_df['Action'==action]].values
        values += list(amounts*prices)  
    orders_df['Values'] = values
    

    The .values method returns a numpy array allowing you to easily multiply element-wise and then you can cumulatively generate a list by 'adding' to it.

    0 讨论(0)
提交回复
热议问题