1

For example I lets say I have the dataframe df with column A containing ints.

If I wanted to change all the values in A so that they all had 1 added to them I would write something like this:

df["A"] = df["A"] + 1

Is there a way to write this so I don't have to write df["A"] twice?

dustyjuicebox
  • 267
  • 2
  • 9

1 Answers1

3

Most of these solutions have been mentioned in comments, so I'm just fleshing them out as answers here.


Option 1
Direct assignment. The most idiomatic approach.

df['A'] += 1

Alternatively, you could use the dot notation for accessing columns:

df.A += 1

This, however, will not work for columns that have spaces in them, or begin with digits.


Option 2
Using df.assign (better if you want a copy, rather than inplace assignment)

df = df.assign(A=df['A'] + 1)

You can also use this in conjunction with df.add as pointed out:

df = df.assign(A=df['A'].add(1))
cs95
  • 379,657
  • 97
  • 704
  • 746