Create a Series in python – pandas

Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, python objects, etc.). In this tutorial we will learn the different ways to create a series in python pandas (create empty series, series from array without index, series from array with index, series from dictionary and scalar value ). The axis labels are called as indexes.

Create an Empty Series:

A basic series, which can be created is an Empty Series. Below example is for creating an empty series.

# Example Create an Empty Series

import pandas as pd
s = pd.Series()
print s

output:

Series([], dtype: float64)

 

 

Create a series from array without index:

Lets see an example on how to create series from an array.

# Example Create a series from array

import pandas as pd
import numpy as np
data = np.array(['a','b','c','d','e','f'])
s = pd.Series(data)
print s

output:

0  a
1   b
2   c
3   d
4   e
5   f
dtype: object

 

 

Create a series from array with index:

This example depicts how to create a series in python with index, Index starting from 1000 has been added in the below example.

# Example Create a series from array with specified index

import pandas as pd
import numpy as np
data = np.array(['a','b','c','d','e','f'])
s = pd.Series(data,index=[1000,1001,1002,1003,1004,1005])
print s

output:

1000   a
1001   b
1002   c
1003   d
1004   e
1005   f
dtype: object

 

 

Create a series from Dictionary

This example depicts how to create a series in python with dictionary. Dictionary keys are used to construct index.

# Example Create a series from dictionary

import pandas as pd
import numpy as np
data = {'a' : 0., 'b' : 1., 'c' : 2.}
s = pd.Series(data,index=['b','c','d','a'])
print s

Index order is maintained and the missing element is filled with NaN (Not a Number). So the output will be

output:

b   1.0
c   2.0
d   NaN
a   0.0
dtype: float64

 

 

Create a series from Scalar value

This example depicts how to create a series in python from scalar value. If data is a scalar value, an index must be provided. The value will be repeated to match the length of index

# create a series from scalar

import pandas as pd
import numpy as np
s = pd.Series(7, index=[0, 1, 2, 3])
print s

output:

0   7
1   7
2   7
3   7
dtype: int64

 

previous Create a Series in python                                                                                                                 next Create a Series in python