Use of `df.sub()` in Pandas (in Python)

pandas
ipython

#1

Hello,

I was trying to learn the basics of pandas and could not understand use of pd.sub.

For any dataframe d and series s what does the function d.sub(s,axis='index') yield ?

Thanks


#2

@mukesh,

In pandas, dataframe.sub is used to subtract a series or dataframe from dataframe. Here we also have option like dataframe.add, dataframe.mul and dataframe.div. Syntaxes for all these are same but these work differently like addition, multiplication, subtraction and division.

Syntax:- DataFrame.div(other, axis=‘columns’, level=None, fill_value=None)

Where
other : Series, DataFrame, or constant
axis : {0, 1, ‘index’, ‘columns’} # For Series input, axis to match Series index on
fill_value : None or float value, default None # Fill missing (NaN) values with this value. If both DataFrame locations are missing, the result will be missing
level : int or name

Example:

Create a dataframe with random numbers of 5 rows and 5 columns

import numpy as np
import pandas as pd
test=pd.DataFrame(np.random.rand(5,4),columns=list('abcd'))
test

Create a series of 5 1’s

temp=[1]*5
temp

[Out]: [1, 1, 1, 1, 1]

Subtracted series temp from dataframe test

test.sub(temp,axis=0) #axis=0 is used to subtract value from each column.

In similar ways, we can perform addition, subtraction, multiplication and division.

Regards,
Imran