Pandas ASSIGN function – use dynamic column name in loop

Question:

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?

Asked By: bananaboy

||

Answers:

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}}
Answered By: sophocles
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.