w3resource

Conditional selection with .loc in Pandas DataFrame

Pandas: Advanced Indexing and Slicing Exercise-10 with Solution

Conditional Selection with loc:

Write a Pandas program to use .loc to select rows based on a condition.

Sample Solution :

Python Code :

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
    'P': [1, 6, 8, 3, 7],
    'Q': [5, 2, 9, 4, 1]
})

# Conditional selection using .loc
result = df.loc[df['P'] > 3]
print(result)

Output:

   P  Q
1  6  2
2  8  9
4  7  1

Explanation:

  • Import pandas library.
  • Create a DataFrame.
  • Use .loc to select rows where column 'P' > 3.
  • Print the results.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Selecting rows by position in Pandas DataFrame.
Next: Setting values with .loc in Pandas DataFrame.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/pandas/conditional-selection-with-dot-loc-in-pandas-dataframe.php