Pandas Series is a one-dimensional marker array capable of holding any type of data (integers, strings, floating-point numbers, python objects, etc.). Shaft labels are collectively referred to as numbering.
Tags don’t have to be unique, but they must be hashable. The object supports both integer-based and tag-based indexes, and provides a number of methods for performing operations involving indexes.
Create an empty Series:
The basic series that can be created is an empty series.
# import pandas as pd
import pandas as pd
# Creating empty series
ser = pd.Series()
print (ser)
Output:
Series([], dtype: float64)
Create a sequence from an array:
In order to create a sequence from an array, we have to import a numpy module, and we have to use the array() function.
# import pandas as pd
import pandas as pd
# import numpy as np
import numpy as np
# simple array
data = np.array([ 'g' , 'e' , 'e' , 'k' , 's' ])
ser = pd.Series(data)
print (ser)
Output:
Create a sequence from an array with an index:
In order to create a sequence from an array with an index, we must provide the index with the same number of elements as in the array.
# import pandas as pd
import pandas as pd
# import numpy as np
import numpy as np
# simple array
data = np.array([ 'g' , 'e' , 'e' , 'k' , 's' ])
# providing an index
ser = pd.Series(data, index = [ 10 , 11 , 12 , 13 , 14 ])
print (ser)
Output:
Create a Series from the list
:
In order to create a Series from a list, we must first create a list before we can create a Series from a list.
import pandas as pd
# a simple list
list = [ 'g' , 'e' , 'e' , 'k' , 's' ]
# create series form a list
ser = pd.Series( list )
print (ser)
Output:
Create a Series from a dictionary
:
In order to create a Series from a dictionary, we must first create a dictionary before we can create a Series using a dictionary. Dictionary keys are used to construct indexes.
import pandas as pd
# a simple dictionary
dict = { 'Geeks' : 10 , 'for' : 20 , 'geeks' : 30 }
# create series from dictionary
ser = pd.Series( dict )
print (ser)
Output:
Create a sequence based on scalar values:
In order to create a sequence from a scalar value, an index must be provided. The scalar values are repeated to match the length of the index.
import pandas as pd
import numpy as np
# giving a scalar value with index
ser = pd.Series( 10 , index = [ 0 , 1 , 2 , 3 , 4 , 5 ])
print (ser)
Output:
Use the NumPy function to create a Series
:
In order to create a Series using the numpy function, we can use a different numpy function, for example
numpy.linspace()
,
numpy.random.radn()
.
# import pandas and numpy
import pandas as pd
import numpy as np
# series with numpy linspace()
ser1 = pd.Series(np.linspace( 3 , 33 , 3 ))
print (ser1)
# series with numpy linspace()
ser2 = pd.Series(np.linspace( 1 , 100 , 10 ))
print ( "\n" , ser2)
Output:
First, your interview preparation enhances your data structure concepts with the Python DS course.