Home > Blockchain >  Pandas If a value exists in one column populate value in different column
Pandas If a value exists in one column populate value in different column

Time:10-07

product group product Record Type Main Product Family
PMX PMX_IA bte-pmx PMX
GTRate FM bt_us-FM GTRate
bte-pmx

I have the above dataframe and have added the column Main Product Family. IF there are values in the column "Product Group" I map these values to the Main Product Family column. If there are null values I need to go off of Record Type.

I have tried the following to populate values in the Main Product Family.

def func(x):
    for i in range(0,len(x)):
       if x.iloc[i,2] == 'bte-pmx':
           x.iloc[i,3] == 'PMX'
    return x

And then I try to map this function to the dataframe but nothing populates in the rows with null values in Main Product Family.

CodePudding user response:

Try this:

df['Main Product Family'] = df['product group'].where(df['product group'].notna(),df['Record Type'])

CodePudding user response:

This seems easier and clearer (I bet faster too)

i = x['Record Type'] == 'bte-pmx'        # select your rows
x.loc[i,'Main Product Family'] == 'PMX'  # set values in those rows
  • Related