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

Main framework for PyTorch music generation model

If your goal is purely symbolic melody generation (e.g., generating MIDI files or notes rather…

1 day ago

affine_grid() in pytorch

According to PyTorch document, In PyTorch, torch.nn.functional.affine_grid generates a 2D or 3D flow field (sampling…

2 months ago

How to create an Android mobile app with a deep learning AI model ?

Creating an Android mobile app with a deep learning AI model involves several key steps:…

11 months ago

Download source files for R Machine learning

Click here to go to source files for R Machine Learning

1 year ago

Python Machine Learning Source Files

Click here to download Python Machine Learning Source Files !

1 year ago

Install PyTorch on Windows

PyTorch is a deep learning package for machine learning, or deep learning in particular for…

1 year ago