Adding a constant number to DataFrame columns in Pandas
Start your free 7-days trial now!
We can add a constant number to DataFrame columns in Pandas using the +
operator or the add(~)
method.
Unless you use the parameters axis
, level
and fill_value
, add(~)
is equivalent to performing addition using the +
operator.
Example
Consider the following DataFrame:
df
A B0 2 41 3 5
All columns
To add 10 to all columns in the DataFrame:
df = df + 10df
A B0 12 141 13 15
By default a new DataFrame is returned, so if you would like to modify the original DataFrame in-place you need to reassign the result to the original variable as in the above example.
Single column
To add 10 to only the "A"
column in the DataFrame:
df["A"] = df["A"] + 10df
A B0 12 41 13 5
Missing values
Consider the following DataFrame:
df
A B0 3.0 41 NaN 5
To add 10 to the whole DataFrame:
df = df + 10df
A B0 13.0 141 NaN 15
Notice that missing values remain missing after the addition, but all other values have 10 added.
Type error
Consider the following DataFrame:
df
A B C0 2 4 Sky1 3 5 Towner
If one of the columns you are adding a constant to is not numeric, you will get a TypeError
:
df = df + 10
TypeError: can only concatenate str (not "int") to str