Home > Net >  pandas math operation with where condition
pandas math operation with where condition

Time:07-23

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?

CodePudding user response:

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()

CodePudding user response:

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]})
  • Related