Alexander Ivanov
Alexander Ivanov

Reputation: 325

How to set values for several columns without loop

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.

Upvotes: 1

Views: 115

Answers (2)

Will
Will

Reputation: 1541

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.

Upvotes: 1

anky
anky

Reputation: 75080

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

Upvotes: 4

Related Questions