search
Search
Unlock 100+ guides
search toc
close
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
Doc Search
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Shrink
Navigate to

# Adding a constant number to DataFrame columns in Pandas

schedule Aug 12, 2023
Last updated
local_offer
PythonPandas
Tags
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
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.

NOTE

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 = pd.DataFrame({"A":[2,3], "B":[4,5]})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 ```
NOTE

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 = pd.DataFrame({"A":[3,np.NaN], "B":[4,5]})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 = pd.DataFrame({"A":[2,3], "B":[4,5], "C":["Sky","Towner"]})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 ```
Edited by 0 others
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
1
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!