Sasi
Sasi

Reputation: 77

How to update existing columns in a dataframe based on multiple conditions on other columns in python?

df1:

Pan_no   Target    Debt_aum  Hml
Xxx        0        5000     Low
YYY        1          0     medium 
ZZZ        0         200     Low
Aaa        1        15000    High
Yyy        1          0      High

Condition:

If the debt_aum =0 and target =1 then hml should be Low for those rows.

Expected Output:

Pan_no   Target   Debt_aum   Hml
Xxx        0        5000     Low
YYY        1          0      Low 
ZZZ        0         200     Low
Aaa        1        15000    High
Yyy        1          0      Low

In SQL I will just write an update statement. In python I am having trouble. I tired doing

for i in df1['hml']:
   if df1[target] == 1 and df1[debt_aum] == 0:
      i = 'Low'
  else:
       i

Upvotes: 2

Views: 96

Answers (3)

SergFSM
SergFSM

Reputation: 1491

a solutiont with loc:

df1.loc[(df1['Debt_aum']==0)&(df1['Target'] == 1)] = 'Low'
df1
'''
  Pan_no Target Debt_aum   Hml
0    Xxx      0     5000   Low
1    Low    Low      Low   Low
2    ZZZ      0      200   Low
3    Aaa      1    15000  High
4    Low    Low      Low   Low

Upvotes: 0

not_speshal
not_speshal

Reputation: 23146

Try with mask:

df["Hml"] = df["Hml"].mask(df["Debt_aum"].eq(0)&df["Target"].eq(1),"Low")

>>> df
  Pan_no  Target  Debt_aum   Hml
0    Xxx       0      5000   Low
1    YYY       1         0   Low
2    ZZZ       0       200   Low
3    Aaa       1     15000  High
4    Yyy       1         0   Low

Upvotes: 2

TheFaultInOurStars
TheFaultInOurStars

Reputation: 3608

IIUC, you can try numpy.where function:

import pandas as pd
import numpy as np
df["Hml"] = np.where(((df["Debt_aum"] == 0) & (df["Target"])), "Low", df["Hml"])
df

Output

Pan_no Target Debt_aum Hml
Xxx 0 5000 Low
YYY 1 0 Low
ZZZ 0 200 Low
Aaa 1 15000 High
Yyy 1 0 Low

Upvotes: 2

Related Questions