Pandas DataFrame add() method with examples

Spread the love

The add() method in pandas adds a specified value to all the values in the dataframe. This is similar to dataframe + other, but with support to substitute a fill_value for missing data in one of the inputs.

Syntax –

dataframe.add(other, axis, level, fill_value)

others – Any single or multiple element data structure, or list-like object.

axis – Whether to compare by the index (0 or ‘index’) or columns (1 or ‘columns’). For Series input, axis to match Series index on.

level – Broadcast across a level, matching Index values on the passed MultiIndex level.

fill_value – Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Examples –

Let’s creates a dataframe.

import pandas as pd
import numpy as np

df = pd.DataFrame({'A':[1, 2, 3, 4, 5, np.nan],
                 'B':[6, 7, 8, 9, 10, np.nan]})
df

1 . Add a value –

Now, let’s say you want to add 10 to each values in the dataframe. One way of achieving this is

df + 10

Another way to add 10 the the dataframe is using the add() method.

df.add(10)

2 . Fill missing Values then add –

If you look at the dataframe, you can see that it contains some missing values. We can first fill these missing values using the fill_value parameter and then add the value.

df.add(10, fill_value=5)

3 . Adding a series –

You can also add a series to the dataframe using the add() method.

# create a series
s1 = pd.Series([11, 12, 13, 14, 15, np.nan])

# add the series to the dataframe
df.add(s1, axis=0)

Rating: 1 out of 5.

Leave a Reply