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

how to create a new column from a row containing specific column name in brackets in pandas

enter image description here

Hello all I have a simple df as shown above. Target column contains column names created with a lambda from other table

targetmain['Target']=targetmain.apply(lambda row: row[row == 1].index.tolist() , axis=1)

What I want to do is to create a new column based on Target column named "Primary", checking what is the target and the number matching the respective column. (eg. for Joe the column "Primary" should be 5, jack 2,avarel 0, william 8)

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

also if the brackets are an issue I can remove them as well.

>Solution :

First remove lists by seelcting first value and then use lookup:

targetmain['Target'] = targetmain['Target'].str[0]

idx, cols = pd.factorize(targetmain['Target'])
df['Primary'] = targetmain.reindex(cols, axis=1).to_numpy()[np.arange(len(targetmain)), idx]

For old pandas versions use DataFrame.lookup:

targetmain['Target'] = targetmain['Target'].str[0]
targetmain['Primary'] = targetmain.lookup(targetmain.index, targetmain['Target'])
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