How to use integer position to access a value from a DataFrame

Overview

To access a single value for a row or column pair in a DataFrame, we can use the integer position of the desired value. To make this possible in Pandas, we use the iat attribute.

The iat attribute returns a single value in a given DataFrame or series by using their integer position or index position in the DataFrame.

Syntax

DataFrame.iat
Syntax for the iat attribute in Pandas

Parameter

The iat does not take any parameter values. Instead, it uses the index position of the desired value in the DataFrame as a parameter.

Return value

The iat attribute returns a single value from a given DataFrame or series.

Example

Let's look at the code below:

import pandas as pd
# creating a list of objects
int_values = [1, 2, 3, 4, 5]
text_values = ['alpha', 'beta', 'gamma', 'delta', 'epsilon']
float_values = [0.0, 0.25, 0.5, 0.75, 1.0]
# creating a dataframe from the list of objects
df = pd.DataFrame({"int_column": int_values, "text_column": text_values,
"float_col": float_values}, index=[1, 2, 3, 4, 5])
# printing the dataframe
print(df)
# accessing the value "delta" present in the 4th row and in the "text_columnm" column
a = df.iat[3, 1]
print(a)

Explanation

  • Line 1: We import the pandas library.
  • Lines 4 to 6: We create a list of objects, text_values, int_values, and float_values.
  • Lines 9 to 10: We create a DataFrame using the list of objects by using pandas.DataFrame(). The name of the DataFrame is df.
  • Line 13: We print the DataFrame, df.
  • Line 16: We access the value in the DataFrame, "delta", which is found in the 4th row (index 3) and on the "text_column" column (index 1). The value is passed to a variable, a.
  • Line 17: We print the value a.

Free Resources