Home > Net >  Pandas ASSIGN function - use dynamic column name in loop
Pandas ASSIGN function - use dynamic column name in loop

Time:11-03

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?

CodePudding user response:

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}}
  • Related