Get index Pandas Python

In this Pandas tutorial, we will learn how to get the index in Pandas DataFrame using Python. Also, we will cover these topics.

  • Find index Pandas DataFrame
  • Get row index Pandas DataFrame
  • Get index values Pandas DataFrame
  • Get index column Pandas DataFrame
  • Python Pandas get index where
  • Get index of max value Pandas Python

Get index Pandas Python

  • In this program, we will discuss how to get the index of a Pandas DataFrame in Python.
  • By using DataFrame.index method we can easily get the index values of a given DataFrame. This method allows you to access the index of the Pandas DataFrame and it will always return an object of type index.

Syntax:

Here is the Syntax of the Dataframe. index() method

DataFrame.index

Note: This method does not take any argument and returns an index value by default index value starts at 0.

Example:

Let’s create an example and check how to get the index in DataFrame

import pandas as pd
Student_info = [('Potter', 278),
            ('George', 163),
            ('Oliva', 129),
            ('John', 145),
            ('Adam', 834),
            ('Hayden',745),
            ('Chris', 981)
            ]
df = pd.DataFrame(Student_info, columns=['Student_name','Student_id'])
new_val = df.index

for x in new_val:
    print(x)

In the above program, we have a DataFrame with a default index, Since there is no specified index value then by default range starts at 0.

In this example first, we have created a list of tuples and then declare a DataFrame object in which we have specified the column name ‘Student_name’ and ‘Student_id’.

Once you will print ‘x’ then the output will display the index values of a DataFrame.

You can refer to the below Screenshot for getting index values

Get index Pandas Python
Get index Pandas Python

Another example to get the index of rows in a DataFrame

In this example, we will discuss how to get the index of a specific row in a DataFrame.

To do this task suppose we have a column of ‘China’ that has “23” at index 0 and no other place, the index list of all rows that stores “23” is [0].

Source Code:

import pandas as pd

df = pd.read_csv("test1.csv")
print(df)
index = df.index
new_val = df["China"] == 23
b = index[new_val]

new_output = b.tolist()

print("Get only rows with china:",new_output)

In the above following given code first, we have imported a pandas module and then create a DataFrame in which we have to assign a CSV file. Once you will print ‘df’ then the output will display the content of the CSV file.

Now use the DataFrame.index method to get the indices of a specific row in a Pandas DataFrame.

Here is the Execution of the following given code

Get index Pandas Python
Get index Pandas Python

Read: Count Rows in Pandas DataFrame

Find index Pandas DataFrame

  • Here we can see how to find the index of an element in Pandas DataFrame.
  • In this example, we have created a numpy random function in which we have assigned a starting and ending value. While creating a DataFrame object it returns a list of index positions.

Source Code:

import pandas as pd
import numpy as np

new_dt = pd.DataFrame(np.random.randint(2,10,size=(10, 3)), columns=list('ZXY'))

print ("Get index of DataFrame")
print(new_dt)

Here is the implementation of the following given code

Find index Pandas DataFrame
Find index Pandas DataFrame

Read: How to delete a column in pandas

How to find the index of a Pandas DataFrame

By using Pandas.Index.get_loc method we can perform this particular task and return a list of index positions.

Syntax:

Here is the Syntax of Pandas.Index.get_loc method

Index.get_loc(key, method=None, tolerance=None
  • It consists of few parameters
    • Key: This Parameter specifies the label
    • Method: This is a optional parameter and by default its value is None.
    • tolerance: The maximum distance from index value for inexact matches and value will be either integer or float.

Example:

import pandas as pd

selected_index = pd.Index(list('uqw'))
new_output =selected_index.get_loc('q')
print(new_output)

In the above code first, we have imported a pandas library, and then we have created a dataframe in which we assign a string value ‘uqw’. Now we want to display the specific index value for ‘q’.

To do this task we use the concept of Pandas.index.get_loc() method. This method will help the user to find the specific index value of a DataFrame.

Here is the Screenshot of the following given code

Find index Pandas DataFrame
Find index Pandas DataFrame

Read: Python Pandas Write DataFrame to Excel

Get row index Pandas DataFrame

  • Here we can see how to get the row index value from Pandas DataFrame.
  • Let’s create a simple DataFrame in which we have assign string values and it can be matched on two methods.
  • In this Program, we have created a simple DataFrame in which we have assigned a columns and list of values. Once you will print ‘new_dt’ then the output will display the index values of “Employee_name” and “Employee_id”.

Source Code:

import pandas as pd

new_dt = pd.DataFrame({"Employee_name": ["George", 
                            "John", 
                            "Micheal", 
                            "Potter", 
                            "Oliva"], 
                    "Employe_id": ["289",
                            "118",
                            "725",
                            "963",
                            "1789"]
                    })

print(new_dt)

Here is the implementation of the following given code

Get row index Pandas DataFrame
Get row index Pandas DataFrame

Get row index of Pandas DataFrame

By iterating the columns, we can perform this particular task. In this method, we will analyze the real datasets that are “test1.csv”. Now we need to get the index of the row of Pandas DataFrame.

Let’s understand and discuss how to get the row index value

Example:

import pandas as pd

new_val = pd.read_csv("test1.csv")
result = new_val.head()
for new_row in result.index:
	print(new_row, end = " ")

Here is the Output of the following given code

Get row index Pandas DataFrame
Get row index Pandas DataFrame

Read: Python Pandas DataFrame Iterrows

Get index values Pandas DataFrame

  • Let us see how to get the index values from Pandas DataFrame.
  • Now let’s take an example and solve this problem by iterating the column names. To do this task first we have created a DataFrame object ‘df’ in which we have assigned a specific column name ‘Numbers’. Once you will print ‘df’ then the output will show the ‘Numbers’ value index of a DataFrame.

Source Code:

import pandas as pd
empoyees = [(89),
            (367),
            (921),
            (178),
            (632),
            (156),
            (176)
            ]

df = pd.DataFrame(empoyees, columns=['Numbers'])
print(df)

You can refer to the below Screenshot for getting the index value

Get index values Pandas DataFrame
Get index values Pandas DataFrame

Read: Python convert DataFrame to list

Get index column Pandas DataFrame

  • In this program, we will discuss how to get index column Pandas DataFrame.
  • By using Pandas.Index.get_loc method we can perform this particular task and return a list of index positions.
  • In Python Pandas.index.get_loc method return integer location and this method works with sorted and unsorted indexes. It will check the condition if the value is not present then it will return the next value to the passed value only if the index values are sorted.

Syntax:

Here is the Syntax of Pandas. index.get_loc() method

Index.get_loc(key, method=None, tolerance=None)

Source Code:

import pandas as pd

new_dict = {'Mangoes': [74, 118, 924,
				918, 802],
		'Cherry': [145, 689, 378,
					18, 16],
		'Banana': [133, 521, 489,
					349, 589]}

df = pd.DataFrame(new_dict)

new_column_name = "Cherry"
new_val = df.columns.get_loc(new_column_name)

print("Index of {} column in given dataframe is : {}".format(new_column_name, new_val))

In the above example, we have imported the Pandas library and then create a dictionary in which we have to assign key-value pair elements.

Now in this example, we will consider a key element as a column name and then declare a DataFrame object.

Now I want to display the index value of the specific column to do this task first I have created a variable ‘new_column_name’ and assign a column name “Cherry”.

Here is the Screenshot of the following given code

Get index column Pandas DataFrame
Get index column Pandas DataFrame

Read: Pandas Delete Column

Python Pandas get index where

  • Let us see how to get the index value of Pandas by using the where function.
  • In Python Pandas the where() method is used to check a Pandas DataFrame and it accepts a condition as an argument. It will check the condition for each value of the Pandas DataFrame if it does not exist in DataFrame then it will be replaced by nan value.

Syntax:

Here is the Syntax of DataFrame.where() method

DataFrame.where
               (
                cond,
                other=nan,
                inplace=False,
                axis=None,
                level=None,
                errors='raise',
                try_cast=Nodefault.no_default
               )

Source Code:

import pandas as pd
import numpy as np

Country_name=['Australia', 'Russia', 'Moscow', 'Newzealand','Switzerland','France']
new_val=[780,521,450,320,800,900]

df = pd.DataFrame({'country':Country_name ,
                   'VALUE':new_val})


new_output = list(np.where(df["VALUE"] >= 800))
print(new_output)

In the above example, we have created two lists ‘Country_name’ and ‘new_val’ along with that we have declared a DataFrame object ‘df’ in which we have assigned the column names.

Now we have to use them where the function to get the index value which is less than 800.

Here is the execution of the following given code

Python Pandas get index where
Python Pandas get index where

Read: How to Convert Pandas DataFrame to a Dictionary

Get index of max value Pandas Python

  • In this program, we will discuss how to get the index of the maximum value in Pandas Python.
  • In Python Pandas DataFrame.idmax() method is used to get the index of the first occurrence of maximum over the given axis and this method will always return the index of the maximum value and if the column or row in the Pandas DataFrame is empty then it will raise a Value Error.

Syntax:

Here is the Syntax of DataFrame.idmax() method

DataFrame.idxmax
                (
                axis=0,
                skipna=True
               )
  • It Consists of few parameters
    • Axis: If the axis value is 1 than it will represent the column wise. If the axis=0 then it will represent the row-wise.
    • skipna: By default its value is ‘True’ and this parameter represents the boolean value(True or False) and excludes all missing values and nan values.

Example:

import pandas as pd

df = pd.DataFrame({"value1": [82, 91, 78], "value2": [88,77,33]})
col_name = df["value1"]
new_output = col_name.idxmax()
print("Get index for mmax value:",new_output)

In the above example, we have considered a DataFrame and get the index for the maximum value in each column by using DataFrame.idxmax() method.

In this program, we have specified the column name “value1” and it will get the index of maximum value.

Here is the output of the following given code.

Get index of max value Pandas Python
Get the index of max value Pandas Python

You may also like to read the following articles.

In this Python Pandas tutorial, we have learned how to get the index in Pandas DataFrame using Python. Also, we have covered these topics.

  • Find index Pandas DataFrame
  • Get row index Pandas DataFrame
  • Get index values Pandas DataFrame
  • Get index column Pandas DataFrame
  • Python Pandas get index where
  • Get index of max value Pandas Python