How to get a value from the cell of a Pandas DataFrame?


To get a value from the cell of a DataFrame, we can use the index and col variables.

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.

  • Print the input DataFrame, df.

  • Initialize the index variable.

  • Initialize the col variable.

  • Get the cell value corresponding to index and col variable.

  • Print the cell value.

Example

 Live Demo

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 1, 9],
      "y": [4, 1, 5, 10],
      "z": [4, 1, 5, 0]
   }
)
print("Input DataFrame is:
"
, df) index = 2 col = "y" cell_val = df.iloc[index][col] print "Cell value at ", index, "for column ", col, " : ", cell_val index = 0 col = "x" cell_val = df.iloc[index][col] print "Cell value at ", index, "for column ", col, " : ", cell_val index = 1 col = "z" cell_val = df.iloc[index][col] print "Cell value at ", index, "for column ", col, " : ", cell_val

Output

Input DataFrame is:
   x  y  z
0  5  4  4
1  2  1  1
2  1  5  5
3  9 10  0

Cell value at 2 for column y: 5
Cell value at 0 for column x: 5
Cell value at 1 for column z: 1

Updated on: 14-Sep-2023

34K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements