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

Asked By: FlyingPickle

||

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.

Answered By: Bimesh Perera

try this:

df["total"] = df[["col1", "col2", "col3"]].sum() * df["price"]

Answered By: Klops
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.