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

Pandas ASSIGN function – use dynamic column name in loop

I have the following pseudocode:


for col in df.columns:
     df.assign('Test_' + str(col) = 1)

This code won’t work. But how do I use a string in the assign operator?

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

>Solution :

You can use ** and do:

df.assign(**{
    "Test_"+col: 1 for col in df.columns
    })

   col1  col2  col3  col4  Test_col1  Test_col2  Test_col3  Test_col4
0     1     0     1     0          1          1          1          1
1     0     0     1     0          1          1          1          1
2     0     1     1     0          1          1          1          1
3     1     0     0     0          1          1          1          1
4     0     0     1     1          1          1          1          1

Setup:

{'col1': {0: 1, 1: 0, 2: 0, 3: 1, 4: 0},
 'col2': {0: 0, 1: 0, 2: 1, 3: 0, 4: 0},
 'col3': {0: 1, 1: 1, 2: 1, 3: 0, 4: 1},
 'col4': {0: 0, 1: 0, 2: 0, 3: 0, 4: 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