1

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?

1 Answer 1

4

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}}
Sign up to request clarification or add additional context in comments.

2 Comments

What is that operator called **{}?
@bananaboy That's dictionary unpacking – python-reference.readthedocs.io/en/latest/docs/operators/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.