Open In App

Change the order of index of a series in Pandas

Suppose we want to change the order of the index of series, then we have to use the Series.reindex() Method of pandas module for performing this task.

Series, which is a 1-D labeled array capable of holding any data.



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

Parameters:



  • data takes ndarrys, list, constants.
  • index values.
  • dtypes for data types.
  • Copy data, default is False.

For knowing more about the pandas Series click here.

Series.reindex() Method is used for changing the data on the basis of indexes.

Syntax: Series.reindex(labels=None, index=None, columns=None, axis=None, method=None, copy=True, level=None, fill_value=nan, limit=None, tolerance=None)
 

For knowing more about the pandas Series.reindex() method click here.

Let’s create a series:




# import required library
import pandas as pd
import numpy as np
 
# create numpy array
data = np.array(["Android dev",
                 "content writing",
                 "competitive coding"])
#create a series
total_series = pd.Series(data,
                         index = [1, 2, 3])
 
# show the series
total_series

Output:

Series

Example 1: 




# import required library
import pandas as pd
import numpy as np
 
# create numpy array
data = np.array(["Android dev",
                 "content writing",
                 "competitive coding"])
# create a series
total_series = pd.Series(data,
                         index = [1, 2, 3])
# reindexing of series
total_series = total_series.reindex(index
                                    = [3, 2, 1])
# show the series
total_series

Output:
 

Example 2: 




# import required library
import pandas as pd
import numpy as np
 
# create numpy array
data = np.array(["Android dev",
                 "content writing",
                 "competitive coding"])
# create a series
total_series = pd.Series(data,
                         index = [1, 2, 3])
# reindexing of series
total_series = total_series.reindex([2, 3, 1])
 
# show the series
total_series

Output:

 


Article Tags :