Home > Back-end >  Pandas mutiply a column by (-1) using another column's valuea as a condition
Pandas mutiply a column by (-1) using another column's valuea as a condition

Time:03-15

Hi I have a data frame with 2 columns one is named NP_x and has values NaN and 'X' and the other one is Amount_x and have int values. What I try to do is that I want to multiply the amount with (-1) where NP_x ='X'

For examnple I have

NP_x   Amount_x
X       2
        5
X       4
X       3

I want to obtain

NP_x   Amount_x
X       -2
        5
X       -4
X       -3

I tried to do this:

df.loc[df_query5['NP_x'] == 'X', 'Amount_x'] = df['Amount_x'].multiply(-1)

How can I resolve this?

CodePudding user response:

Please try this:

import numpy as np
df['Amount_x'] = np.where(df['NP_x']=='X',df['Amount_x']*-1,df['Amount_x'])

CodePudding user response:

There you go using mul (mutiply) operator :

df.loc[df['NP_x'] == 'X', 'Amount_x'] = df['Amount_x'].mul(-1)

CodePudding user response:

See: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html

>>> df.loc[df['shield'] > 6, ['max_speed']]
            max_speed
sidewinder          7

Therefore, you can use the following code:
df.loc[df['NP_x'] == 'X', ['Amount_x']] = - df.loc[df['NP_x'] == 'X', ['Amount_x']]

CodePudding user response:

look my example

import pandas as pd
df = pd.DataFrame([["X", 2], ["Y", 3], ["X", 5]], columns=list("AB"))

df:

  A   B
0 X   2
1 Y   3
2 X   5
df["B"] = df["B"].mask(df["A"]=="X", -df["B"])

df:

A B
0 X   -2
1 Y    3
2 X   -5

CodePudding user response:

Use DataFrame.loc:

df.loc[df['NP_x']=='X', 'Amount_x'] *= -1

working same like:

df.loc[df['NP_x']=='X', 'Amount_x'] = df.loc[df['NP_x']=='X', 'Amount_x'] * -1
  • Related