Python Pandas Series with examples

Python Pandas Series

A Series is a one-dimensional labeled array. It can hold any type of data like Integer, Float, String, Python objects, etc. The label is called the index.

How to create a Series

A series can be created using various inputs like-

  • Array
  • Dictionary
  • constant

Create a Series from an array

If data is an array, then the index must be of the same length. If no index is passed, then by default index will be range(n) where n is the array length.

Example : 1.

#imports the pandas library and aliasing as pd
import pandas as pd
import numpy as np
data = np.array([‘a’,’b’,’c’,’d’,’e’])
sr=pd.Series(data)
print (sr)

Its output is as follows-

0a
1b
2c
3d
4e

We did not pass any index. By default it assigned the index values ranging from 0 to 4, which is length(data) -1, i.e. 0 to 4.

Example : 2.

#imports the pandas library and aliasing as pd
import pandas as pd
import numpy as np
data = np.array([‘a’,’b’,’c’,’d’,’e’])
sr=pd.Series(data, index=[101,102,103,104,105])
print (sr)

Its output is as follows-

101a
102b
103c
104d
105e

Create a Series from a dictionary

A dictionary can be passed as input and if no index is specified, then the dictionary keys are taken in a sorted order to construct the index.

Example :

#imports the pandas library and aliasing as pd
import pandas as pd
data = {‘a’ : 0, ‘b’ : 1, ‘c’ : 2, ‘d’ : 3}
sr=pd.Series(data)
print (sr)

Its output is as follows-

a0
b1
c2
d3

Create a Series from constant

An index must be provided if the data is a scalar value or constant. The value will be repeated to match the length of the index.

Example : 

#imports the pandas library and aliasing as pd
import pandas as pd
import numpy as np
sr=pd.Series(4, index=[0,1,2,3])
print (sr)

Its output is as follows-

04
14
24
34

Leave a Reply

Your email address will not be published.

Follow by Email
Facebook
Instagram