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.
Submitted by Pranit Sharma, on September 09, 2022

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.

Getting scalar value on a cell using conditional indexing

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.

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 code 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:

Get scalar value on a cell using conditional indexing

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.