Mathematical operations between Pandas Series in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental level, click here for more details.

Series is the simplest data structure from Pandas library in Python. It stores usually labeled data, i.e. a list of values and and a list of labels combined and saved in an individual object. When we perform mathematical operations, such as addition or subtraction between two Series, the operation will be carried out only with those values that have common corresponding labels in both Series. Otherwise, the corresponding value in the resulting Series will be NaN (Not a Number) value(s). In the next example, we show two examples of this mechanism implemented in Python IDE.

#Import Pandas module
import pandas as pd
#create a Series S1, with input from a dictionary
D1 = {'var1':25, 'var2': 32, 'var3': 8, 'var4': 19}
S1 = pd.Series(D1)
S1
#output
var1    25
var2    32
var3     8
var4    19
dtype: int64
#similarly, we create a second Series, having same labels as the first
D2 = {'var1':17, 'var2': 301, 'var3': 16, 'var4': 201}
S2 = pd.Series(D2)
S2
#output
var1     17
var2    301
var3     16
var4    201
dtype: int64
#we perform addition of these two Series
S1 + S2
#result is a Series too, with the values coming from addition 
#of corresponding values in both Series
var1     42
var2    333
var3     24
var4    220
dtype: int64
#Now we create a third Series, with some new labels
D3 = {'var1':11, 'var3': 28, 'var5': 36, 'var6': 9}
S3 = pd.Series(D3)
S3
#output
var1    11
var3    28
var5    36
var6     9
dtype: int64
#then we perform addition between the first and third Series
S1 + S3
#resulting Series have labels that are out-union of these two
#Series' labels, and some values have values NaN, because
#those labels are not found in both inputting Series
var1    36.0
var2     NaN
var3    36.0
var4     NaN
var5     NaN
var6     NaN
dtype: float64

You can also watch videos on our YouTube channel for more understanding of Python programming skills.

wilsonzhang746

Recent Posts

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago