Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

adjust values which are associated with a string from a different column

I have a dataframe which I’d like to adjust the values which are associated with a string from a different column. Example, all values in column ‘wgt’ that is associated with ‘joe’ in the ‘name’ column to multiply 1.10.

original df

╔══════╦═════╗
β•‘ name β•‘ wgt β•‘
╠══════╬═════╣
β•‘ joe  β•‘  10 β•‘
β•‘ gary β•‘   8 β•‘
β•‘ pete β•‘  12 β•‘
β•‘ pete β•‘  13 β•‘
β•‘ pete β•‘  14 β•‘
β•‘ joe  β•‘  11 β•‘
β•‘ gary β•‘   7 β•‘
β•‘ gary β•‘   5 β•‘
β•‘ gary β•‘   7 β•‘
β•šβ•β•β•β•β•β•β•©β•β•β•β•β•β•

adjusted df

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

╔══════╦═════╗
β•‘ name β•‘ wgt β•‘
╠══════╬═════╣
β•‘ joe  β•‘  11 β•‘
β•‘ gary β•‘   8 β•‘
β•‘ pete β•‘  12 β•‘
β•‘ pete β•‘  13 β•‘
β•‘ pete β•‘  14 β•‘
β•‘ joe  β•‘ 12.1β•‘
β•‘ gary β•‘   7 β•‘
β•‘ gary β•‘   5 β•‘
β•‘ gary β•‘   7 β•‘
β•šβ•β•β•β•β•β•β•©β•β•β•β•β•β•

code for sample df

import pandas as pd
data = {'name':['joe','gary','pete','pete','pete','joe','gary','gary','gary'
],'wgt':[10,8,12,13,14,11,7,5,7,]}
df = pd.DataFrame(data)
df

thanks in advance

>Solution :

df['wgt'] = np.where(df.name == "joe", df.wgt * 1.1, df.wgt)

or

df.loc[df.name == "joe", "wgt"] *= 1.1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading