How to get scalar value on a cell using conditional indexing?

Given a pandas dataframe, we have to get scalar value on a cell using conditional indexing. By Pranit Sharma Last updated : September 30, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose, we have a DataFrame with two columns A and B, we need to get scalar values on column B which is dependent on column A.

Getting scalar value on a cell using conditional indexing

For this purpose, we will first access both the row and column indices using the .loc[] property. By this, we will be able to apply a condition on column A and hence we can also select all the values of B where the condition is met for A.

Let us understand with the help of an example,

Python program to get scalar value on a cell using conditional indexing

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {
    'A':[2,3,2,4,2,5,2,6],
    'B':['Hello','Hi','India','Cricket','Great','Country','Victory','Nice']
}

# Creating DataFrame
df = pd.DataFrame(d)

# Display the DataFrame
print("Original DataFrame:\n",df,"\n")

# Getting scalar values on B
result = df.loc[df['A'] == 2, 'B']

# Display result
print("Result:\n",result,"\n")

Output

The output of the above program is:

Get scalar value on a cell using conditional indexing

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.