Pandas dataframe multiple and sum row wise
Question:
I have a pandas df of the following format
Market ID Col1 Col2 Col3 Price Sum_Price
USA 100 0.49 0.5 0.5 100 149
EU 200 0.25 0.25 0.75 100 125
Essentially Sum_Price
is equal to (Col1*Price+Col2*Price+Col*Price)
I have tried df.iloc[:,2:4]*df.iloc[:,5]
but it padded a few extra columns, which I am not sure of the behaviour…
Thanks
Answers:
df['Sum_Price'] = df[['Col1', 'Col2', 'Col3']].multiply(df['Price'], axis=0).sum(axis=1)
The values in Col1, Col2, and Col3 are first multiplied by the values in the Price column using the multiply()
function in the line that calculates the Sum_Price. The sum()
function with axis=1
is then used to add the result across all rows. Finally, the DataFrame receives the new Sum_Price column.
try this:
df["total"] = df[["col1", "col2", "col3"]].sum() * df["price"]
I have a pandas df of the following format
Market ID Col1 Col2 Col3 Price Sum_Price
USA 100 0.49 0.5 0.5 100 149
EU 200 0.25 0.25 0.75 100 125
Essentially Sum_Price
is equal to (Col1*Price+Col2*Price+Col*Price)
I have tried df.iloc[:,2:4]*df.iloc[:,5]
but it padded a few extra columns, which I am not sure of the behaviour…
Thanks
df['Sum_Price'] = df[['Col1', 'Col2', 'Col3']].multiply(df['Price'], axis=0).sum(axis=1)
The values in Col1, Col2, and Col3 are first multiplied by the values in the Price column using the multiply()
function in the line that calculates the Sum_Price. The sum()
function with axis=1
is then used to add the result across all rows. Finally, the DataFrame receives the new Sum_Price column.
try this:
df["total"] = df[["col1", "col2", "col3"]].sum() * df["price"]