Pandas DataFrame - Access a Single Value


DataFrame - Access a Single Value

You can access a single value from a DataFrame in two ways.

Method 1: DataFrame.at[index, column_name] property returns a single value present in the row represented by the index and in the column represented by the column name.

Method 2: Or you can use DataFrame.iat[row_position, column_position] to access the value present in the location represented by the row position row_position and column position column_position, irrespective of the row and column labels.

In this tutorial, we will go through examples using DataFrame.at() and DataFrame.iat(), where we shall access a single value from DataFrame.

Video Tutorial

https://youtu.be/8K_aJPx7-E8?si=cbEhLXE3msPmEbkb

Examples

1. Get a value in DataFrame using at[]

In this example, we will initialize a DataFrame and use DataFrame.at property to access a value.

Python Program

import pandas as pd

df1 = pd.DataFrame({'A': ['aa', 'bb'],
                    'M': ['cc', 'dd'],
                    'C': ['ee', 'ff']},
                   index=[2, 5])

#value at index 2 and column name 'M'
value1 = df1.at[2, 'M']
print(value1)

#value at index 5 and column name 'A'
value2 = df1.at[5, 'A']
print(value2)

Output

cc
bb

2. How to get value from DataFrame that is initialised without specific index

In this example, we take a DataFrame initialized with no index. If no index is provided, you can consider index to be starting at 0 and increment in steps of 1 with each successive row.

Python Program

import pandas as pd

df1 = pd.DataFrame({'A': ['aa', 'bb'],
                    'M': ['cc', 'dd'],
                    'C': ['ee', 'ff']})

value1 = df1.at[0, 'C']
print(value1)

value2 = df1.at[1, 'A']
print(value2)

Output

ee
bb

3. Get value from DataFrame using assumed index

In this example, we take a DataFrame initialized with no index. If no index is provided, you can consider index to be starting at 0 and increment in steps of 1 with each successive row.

Python Program

import pandas as pd

df1 = pd.DataFrame({'A': ['aa', 'bb'],
                    'M': ['cc', 'dd'],
                    'C': ['ee', 'ff']},
                   index=[2, 5])

#value at row position 0, column position 1
value1 = df1.iat[0, 1]
print(value1)

#value at row position 1, column position 1
value2 = df1.iat[1, 1]
print(value2)

Output

cc
dd

Summary

In this tutorial of Python Examples, we learned how to access a value from DataFrame using axis.