Python Pandas Series with examples | How to create Pandas Series | Create a series from Array, Dict, Scaler

Python Pandas Series Create a series from Array, Dict, Scaler

 

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.

Pandas.Series

A Pandas Series can be created using the following constructors-

pandas.Series ( data, index, dtype, copy)

ParameterDescription
datadata takes various forms like ndarray, list, constants
indexIndex values must be unique. By default np.arrange(n)
dtypeit is a data type
copyCopy data. Default false

How to create a Pandas Series

A Pandas 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-

 

0 a
1 b
2 c
3 d
4 e
 
 
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-

 

101 a
102 b
103 c
104 d
105 e
 

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-

 

a 0
b 1
c 2
d 3
 

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
sr=pd.Series(4, index=[0,1,2,3])
print (sr)

 
Its output is as follows-

 

0 4
1 4
2 4
3 4

If you like my post please share it with your friends by simply clicking the below social media button, and don’t forget to comment so we will update ourselves.

Share in a Single Click

Leave a Reply

Your email address will not be published. Required fields are marked *