How to specify an index while creating a Series in Pandas?

PandasServer Side ProgrammingProgramming

Pandas series is 1-Dimensional ndarray with labeled data, which means every value present in a series is having a label representation which is nothing but each data have thor on index values.

The index can be label names (object data) or it can be values. By default, it will assign an index value from 0 - n-1 (n is the length of series values). And it has the ability to define index values.

Pandas Series function has an index keyword for specifying index values, and it takes input as an array with any kind of data in it. The data can be integers, floating-point numbers, text data, DateTime, and more.

Let’s see how we can specify index values at the time of Series creation.


import pandas as pd

Countries = ['Australia', 'Iceland', 'India', 'United Kingdom', 'United States']
Capitals = ['Canberra', 'Reykjavik', 'New Delhi', 'London', 'Washington D.C']

# create series
s = pd.Series(Capitals, index=Countries)



The expected result of this above code is a pandas Series with labeled index and text data. Here the index values are the list of names of some countries and data is respected capital cities for those countries.

We have created a two-python list for holding country names and capital city names. And sent those two lists pandas Series Contractor (pd.Series() function). Capital city names are Series data and country names are indexes.

Specifying index names can be achieved by assigning a python list (countries list) to the index keyword of the pandas Series function. One thing we should remember here is the length of index data must be the same as the length of series data. Otherwise, it will raise ValueError.


Australia              Canberra
Iceland               Reykjavik
India                 New Delhi
United Kingdom           London
United States    Washington D.C
dtype: object

Both indexes and values present in this above output block are object data types. In the above example, we have specified index labels separately at the time of Series creation.


# importing pandas packages
import pandas as pd

dictionary = {'a':'A','c':"C",'d':'D','e':'E'}

#creating a series with null data
s_obj = pd.Series(dictionary)



If we use the python dictionary as data to the pandas Series constructor then it will take keys of the dictionary as indexes and values as elements of the series object.


a   A
c   C
d   D
e   E
dtype: object

We can specify the indexes of a series object by using the keys of the python dictionary.

Updated on 17-Nov-2021 07:28:03