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

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

    To make things neat, I take Hayden's solution but make a small function out of it.

    def create_value(row):
        if row['Action'] == 'Sell':
            return row['Prices'] * row['Amount']
        else:
            return -row['Prices']*row['Amount']
    

    so that when we want to apply the function to our dataframe, we can do..

    df['Value'] = df.apply(lambda row: create_value(row), axis=1)
    

    ...and any modifications only need to occur in the small function itself.

    Concise, Readable, and Neat!

提交回复
热议问题