pandas math operation with where condition

Question:

I want to do math on a condition in a dataframe, but I couldn’t.

my code:

open_position=df.loc[df['sale_price'].isna(), 'purchase_price'*'amount'].sum()

I want to do. Multiply df['purchase_price'] and df['amount'] in rows where df['sales_price'] is NaN and get the sum of all these.

it gives the following error.

TypeError: can't multiply sequence by non-int of type 'str'

Can you help with this?

Asked By: Oguz Han

||

Answers:

IIUC, you can use:

df.loc[df['sale_price'].isna()].apply(lambda row: row['purchase_price'] * row['amount'], axis=1).sum()

Test dataframe:

df = pd.DataFrame({'sale_price':[10, np.nan, 30], 'purchase_price':[5, 15, 25], 'amount':[1, 2, 3]})
Answered By: René

Try this:

df.loc[df['sale_price'].isna(), 'purchase_price'].mul(df['amount']).sum()

or

df['product'] = df['purchase_price'] * df['amount']
df.loc[df['sale_price'].isna(), 'product'].sum()
Answered By: Rabinzel
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.