Home > Net >  How to replace column values with values in another column based on condition?
How to replace column values with values in another column based on condition?

Time:08-04

If the "type" column value is tumor, I want to replace it with value in the "admin.disease_code" column.

Sample data:

admin.disease_code Col2 Col3 type
0 hello m n tumor
1 bye o p a
2 thanks q r b

Expected output:

admin.disease_code Col2 Col3 type
0 hello m n hello
1 bye o p a
2 thanks q r b

Code:

   # If "type" is tumor, replace with value in "admin.disease_code"

    meth_clin_sub_nt_kipan.loc[meth_clin_sub_nt_kipan["type"] == "tumor", "admin.disease_code"] = meth_clin_sub_nt_kipan.loc[meth_clin_sub_nt_kipan["admin.disease_code"]]

CodePudding user response:

You can use np.where:

import numpy as np
meth_clin_sub_nt_kipan['type'] = np.where(meth_clin_sub_nt_kipan["type"] == "tumor", [meth_clin_sub_nt_kipan["admin.disease_code"], meth_clin_sub_nt_kipan['type'])

CodePudding user response:

df
###
  admin.disease_code Col2 Col3   type
0              hello    m    n  tumor
1                bye    o    p      a
2             thanks    q    r      b
3               rock    a    z  tumor
df['type'] = np.where(
    df['type'] == 'tumor', 
    df['admin.disease_code'], 
    df['type']
)
df
###
  admin.disease_code Col2 Col3   type
0              hello    m    n  hello
1                bye    o    p      a
2             thanks    q    r      b
3               rock    a    z   rock
  • Related