1

Pandas: Get Cell Value from a Dataframe

 2 years ago
source link: https://thispointer.com/pandas-get-cell-value-from-a-dataframe/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Pandas: Get Cell Value from a Dataframe

This article will discuss different ways to get a cell value from a Pandas Dataframe in Python.

Table of Contents:

First of all, we will create a Dataframe from a list of columns,

import pandas as pd
# List of Tuples
students = [('jack', 34, 'Sydeny', 'Australia'),
('Riti', 30, 'Delhi', 'France'),
('Vikas', 31, 'Mumbai', 'India'),
('Neelu', 32, 'Bangalore', 'Germany'),
('John', 16, 'New York', 'US'),
('Mike', 17, 'las vegas', 'US')]
# Create a DataFrame from list of tuples
df = pd.DataFrame( students,
columns=['Name', 'Age', 'City', 'Country'],
index=['a', 'b', 'c', 'd', 'e', 'f'])
print(df)
import pandas as pd

# List of Tuples
students = [('jack',  34, 'Sydeny',    'Australia'),
            ('Riti',  30, 'Delhi',     'France'),
            ('Vikas', 31, 'Mumbai',    'India'),
            ('Neelu', 32, 'Bangalore', 'Germany'),
            ('John',  16, 'New York',  'US'),
            ('Mike',  17, 'las vegas', 'US')]

# Create a DataFrame from list of tuples
df = pd.DataFrame( students,
                   columns=['Name', 'Age', 'City', 'Country'],
                   index=['a', 'b', 'c', 'd', 'e', 'f'])

print(df)

Contents of this Dataframe are as follows,

Name Age City Country
a jack 34 Sydeny Australia
b Riti 30 Delhi France
c Vikas 31 Mumbai India
d Neelu 32 Bangalore Germany
e John 16 New York US
f Mike 17 las vegas US
    Name  Age       City    Country
a   jack   34     Sydeny  Australia
b   Riti   30      Delhi     France
c  Vikas   31     Mumbai      India
d  Neelu   32  Bangalore    Germany
e   John   16   New York         US
f   Mike   17  las vegas         US

Now we will explore different techniques to fetch a cell value from this dataframe using label names or index positions or conditions.

Get Cell Value of a Pandas Dataframe using row & column number

We can fetch a cell value from a Dataframe based on its index positions i.e. its row and column number. An important point to remember is that indexing starts from zero. It means the index position/number of Nth row or column will be N-1. For example,

Looking for a Career in Data Science or Machine Learning with Python?

Get a Professional Certificate in data Science by IBM. Build data science skills, learn Python & SQL, analyze & visualize data, build machine learning models. No degree or prior experience required. Checkout the detailed review.

Explore a new career path with a 7 day free trial.

  • 3rd row of the Dataframe is row number 2
  • 4th Column of the Dataframe is column number 3.

To fetch the cell value by row/column number, we have different techniques i.e, either using Dataframe.iat[] or Dataframe.iloc[]. Let’s discuss them one by one,

Get a Cell value using Dataframe.iat[]

In Pandas, the Dataframe provides an attribute iat[] to access a single cell value based on its row & column numbers i.e.

DataFrame.iat[row_number, column_number]
DataFrame.iat[row_number, column_number]

It returns the cell value at the given row & column number. But if any of the given index positions/number is out of bound, it can give IndexError. Let’s understand by an example, fetch the cell value at the 3rd row and 4th column,

row_index_pos = 2
column_index_pos = 3
# Get Cell Value at 3rd row and 4th column
# (Index positions starts from 0)
value = df.iat[row_index_pos,column_index_pos]
print (value)
row_index_pos    = 2
column_index_pos = 3

# Get Cell Value at 3rd row and 4th column
# (Index positions starts from 0)
value = df.iat[row_index_pos,column_index_pos]

print (value)

Output:

India
India

It returned the cell value at the 3rd row and 4th column of the DataFrame as a string.

Important Point:

As Row and Column numbers start from 0 in DataFrame, row number 2 points to the third row of dataframe and column number 3 points to the fourth column of DataFrame.

Get a Cell value using Dataframe.iloc[]

In Pandas, the Dataframe provides a property iloc[], to select the subset of Dataframe based on position indexing. Contents of the subset will be decided based on the provided index positions/numbers of rows & columns. Although we can select single or multiple rows & columns using it. But today, we will choose a single cell using it with the following syntax,

DataFrame.iloc[row_number, column_number]
DataFrame.iloc[row_number, column_number]

For example, let’s fetch the cell value at the 3rd row and 4th column of the Dataframe using iloc[]

row_index_pos = 2
column_index_pos = 3
# Get Cell Value at 3rd row and 4th column
# (Index positions starts from 0)
value = df.iloc[row_index_pos , column_index_pos]
print (value)
row_index_pos    = 2
column_index_pos = 3

# Get Cell Value at 3rd row and 4th column
# (Index positions starts from 0)
value = df.iloc[row_index_pos , column_index_pos]

print (value)

Output:

India
India

It returned the cell value at the 3rd row and 4th column of the DataFrame.

Important Point:

As indexing starts from 0 in DataFrame, the index position of the 3rd row is 2, and for the 4th column, it is 3.

Get Cell Value of a Pandas Dataframe using row & column labels/names

We can fetch a cell value from a Dataframe based on row and column names using loc[] and at[] attributes. Let’s discuss them one by one.

Get call value using loc[] in Pandas Dataframe

In Pandas, the Dataframe provides a property loc[], to select the subset of Dataframe based on row and column names/labels. Although, we can choose single or multiple rows & columns using it. But today, we will select a single cell using it with the following syntax,

DataFrame.loc[row_label, column_name]
DataFrame.loc[row_label, column_name]

For example, let’s fetch the cell value at row ‘c’ and column ‘Age’ of the Dataframe using iloc[]

row_label = 'c'
column_name = 'Age'
# Get cell value at row 'c' and column 'Age'
value = df.loc[row_label, column_name]
print (value)
row_label   = 'c'
column_name = 'Age'

# Get cell value at row 'c' and column 'Age'
value = df.loc[row_label, column_name]

print (value)

Output:

31

It returned the value at row ‘c’ and column ‘Age’ of the DataFrame as int.

Get call value using at[] in Pandas Dataframe

In Pandas, the DataFrame provides a property at[], to access the single values from a Dataframe by their row and column label name. The syntax is as follows,

pandas.DataFrame.at[row_label , column_name]
pandas.DataFrame.at[row_label , column_name]

We will get the value of single cell using it. For example, let’s get cell value at row ‘c’ and column ‘Age’ of the DataFrame,

row_label = 'c'
column_name = 'Age'
# Get cell value at row 'c' and column 'Age'
value = df.at[row_label, column_name]
print (value)
row_label   = 'c'
column_name = 'Age'

# Get cell value at row 'c' and column 'Age'
value = df.at[row_label, column_name]

print (value)

Output:

31

It returned the value at row ‘c’ and column ‘Age’ of the DataFrame as int.

Pandas: Get cell value based on condition

We can select a cell value from a column based on conditions on other columns. For example, get cell value of column ‘Name’, where column ‘Age’ is 32,

# Get cell value of column 'Name', where column 'Age' is 32
values = df[df['Age'] == 32]['Name'].tolist()
if len(values) > 0:
print (values[0])
# Get cell value of column 'Name', where column 'Age' is 32
values = df[df['Age'] == 32]['Name'].tolist()

if len(values) > 0:
    print (values[0])

Output:

Neelu
Neelu

Using df[df[‘Age’] == 32] it selected only those rows where column ‘Age’ has value 32. Then, it fetched the values of column ‘Name’ and then selected the first cell’s value from it.

Get the value of the first cell of a Column

To get the value of any column’s first cell, we first need to select the column as a Series object and then fetch the first entry from it. For example, let’s fetch the value of the first cell from column ‘Age’,

# Get value of first cell of Column 'Age'
value = df['Age'].values[0]
print (value)
# Get value of first cell of Column 'Age' 
value = df['Age'].values[0]

print (value)

Output:

34

It returned the value of the first cell of column ‘Age’.

Summary

Today we learned about different techniques to fetch a cell value from a Pandas Dataframe in Python.

Advertisements


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK