How To Retrieve The First Row Meeting Conditions In Pandas?

We are given a DataFrame in Pandas and need to retrieve the first row that meets certain conditions. In this article, we will explore all the possible approaches to retrieve the first-row meeting conditions in pandas.

Retrieve the First Row Meeting Conditions in Pandas

Below are the possible approaches to retrieve the first-row meeting conditions in pandas in Python:

  • Using loc function
  • Using query function
  • Using Boolean Indexing

Retrieve The First Row Meeting Conditions In Pandas Using loc function

In this example, we are using the loc method to filter rows where the score column is greater than 80, and then selecting the first row from the filtered DataFrame using iloc[0].

Python
import pandas as pd

df = pd.DataFrame({
    'name': ['w3wiki', 'CodingForAll', 'CodeWars'],
    'score': [85, 90, 78],
    'city': ['Noida', 'San Francisco', 'Los Angeles']
})

first_row = df.loc[df['score'] > 80].iloc[0]
print(first_row)

Output
name     w3wiki
score               85
city             Noida
Name: 0, dtype: object

Retrieve The First Row Meeting Conditions In Pandas Using query function

In this example, we are using the query method to filter rows where the score is greater than 80, and then retrieving the first row from the filtered results using iloc[0].

Python
import pandas as pd

df = pd.DataFrame({
    'name': ['w3wiki', 'CodingForAll', 'CodeWars'],
    'score': [85, 90, 78],
    'city': ['Noida', 'San Francisco', 'Los Angeles']
})

first_row = df.query('score > 80').iloc[0]
print(first_row)

Output
name     w3wiki
score               85
city             Noida
Name: 0, dtype: object

Retrieve The First Row Meeting Conditions In Pandas Using Boolean Indexing

In this example, we are using boolean indexing to filter rows where the score is greater than 80, and then using head(1) to get the first row, followed by iloc[0] to access it.

Python
import pandas as pd

df = pd.DataFrame({
    'name': ['w3wiki', 'CodingForAll', 'CodeWars'],
    'score': [85, 90, 78],
    'city': ['Noida', 'San Francisco', 'Los Angeles']
})

first_row = df[df['score'] > 80].head(1).iloc[0]
print(first_row)

Output
name     w3wiki
score               85
city             Noida
Name: 0, dtype: object

Contact Us