1

How can I set values for several columns without loop?

df.loc[:, ['test2', 'test3']] = 0

or

df[['test2', 'test3']] = 0

I expect it to set values 0 in columns 'test2' and 'test3', but it returns the error, that there is no such columns in the df.

0

2 Answers 2

4

If you are trying to create new columns you can use df.assign():

df.assign(test1=0,test2=0)

This will create 2 columns with values as 0

Sign up to request clarification or add additional context in comments.

1 Comment

Dont forget to assign it back to the df. df=df. assign(..)
1

df.assign() is a great way as suggested by @anky_91 to do a bunch of columns at once.

Another explicit way is direct column assignment but then it's column by column

df["NewCol1"] = 0
df["NewCol2"] = 0

Sometimes it's convenient for when you need a single new column.

Comments

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.