CBSE CS and IP

CBSE Class 11 & 12 Computer Science and Informatics Practices Python Materials, Video Lecture

Pandas Series Index Parameter

PANDAS Series Method Index Parameter

Series Method Prototype:

<Series Object> = pandas.Series(data=Noneindex=None, dtype=None, name=None, copy=False, fastpath=False)

  • In this post, we are going to discuss index parameter.
  • To know how to use data parameters click here

The Series method gives the default indexes as 0,1,2 ....etc. In this post, I am going to discuss how to provide user-defined indexes using index Parameter of the Series Method. It is used to provide the data labels for data values. The number of indexes should be the same as the number of data values. The indexes can be provided in the following three ways:
  • The Index taken by Dictionary
  • Specifying Index Using List
  • Indexes with Scalar Data Value

a) The index taken by Dictionary

If we are providing the data in the form of a dictionary, then the keys of the dictionary will become the indexes and values of the dictionary will become data of the Series.
import pandas as pd
d = {'A':1, 'B':2, 'C':3}
print(d)
s = pd.Series(d)
print(s)
print(type(s))

'''
Output:
------
{'A': 1, 'B': 2, 'C': 3}

A    1
B    2
C    3
dtype: int64

<class 'pandas.core.series.Series'>
'''

b) Specifying Index Using List

We can provide indexes using a List, the number of elements in the list should be the same as the number of data values. As shown in the example below the index are X, Y and Z and the data elements are 1, 2 and 3.
import pandas as pd
l = [1,2,3]
s = pd.Series(data= l, index = ['X','Y','Z'])
print(s)
'''
Output
------
X    1
Y    2
Z    3
dtype: int64
'''

l = [1,2,3]
s = pd.Series(l, ['X','Y','Z'])
print(s)
'''
Output
------
X    1
Y    2
Z    3
dtype: int64
'''

Note: Length of Data and Index Should be same. Otherwise, Python will show an error.

c) Indexes with Scalar Value

If we are creating the Series with Scalar Value, then we can provide indexes in the form of a list. The total values in the Series will depend upon the number of elements in the index. For example, you can see the code below. In this code, the scalar value is "Hello" and there are three elements in Series s, because we have provided three indexes.    
import pandas as pd
s = pd.Series("Hello",[1,2,3])
print(s)

'''
#Output:
1    Hello
2    Hello
3    Hello
dtype: object
'''

For more Details Wath the following Video:

No comments:

Post a Comment