How to add a constant number to a DataFrame column with pandas in python ?

Active April 14, 2020    /    Viewed 25660    /    Comments 0    /    Edit


Example of how to add a constant number to a DataFrame column with pandas in python

Create a simple Data frame

Let's create a data frame with pandas called df:

>>> import pandas as pd
>>> import numpy as np
>>> data = np.arange(1,13)
>>> data = data.reshape(3,4)
>>> df = pd.DataFrame(data=data,columns=['a','b','c','d'])
>>> df
   a   b   c   d
0  1   2   3   4
1  5   6   7   8
2  9  10  11  12

Add a constant number to each column elements

Let's select the column b for example:

>>> df['b']
0     2
1     6
2    10

to add 10 to each element, a solution is to do:

>>> df['b'] = df['b'] + 10
>>> df
   a   b   c   d
0  1  12   3   4
1  5  16   7   8
2  9  20  11  12

References

Links Site
Apply a function to a single column in Dataframe thispointer.com
pandas.DataFrame.apply pandas doc


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount