Zubo
Zubo

Reputation: 1593

Pandas: shorten notation for simple operations on multiple columns

Is there a good way to shorten this:

df.a = df.a / 2
df.b = df.b / 2
df.c = df.c / 2

According to this, something like

df[['A','B','C']] = df[['A', 'B','C']].apply(lambda a: a / 2)

should be avoided.

Upvotes: 1

Views: 50

Answers (2)

ChanMan99
ChanMan99

Reputation: 11

Try something like this to take advantage of vectorization.

df[['A','B','C']]/2

Upvotes: 1

Kartikeya Sharma
Kartikeya Sharma

Reputation: 1383

You can easily do it like this

df[['A','B','C']] = df[['A','B','C']]/2

Upvotes: 2

Related Questions