Q:

How to select rows from a DataFrame based on column values using loc property?

belongs to collection: Python Pandas Programs

0

pandas.DataFrame.loc Property

This property is primarily label-based and used to access a group of rows and columns by label(s) or a boolean array.

Syntax:

property DataFrame.loc

Let us begin with an example to understand how we can select a row based on its column value.

DataFrame.loc[df['col-name'] == value]

To work with Python Pandas, we need to import the pandas library. Below is the syntax,

import pandas as pd

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Python code to select rows from a DataFrame based on column values using loc property

Example 1:

# Importing pandas package
import pandas as pd

# Creating a dictionary of student marks
d = {
    "Peter":[65,70,70,75],
    "Harry":[45,56,66,66],
    "Tom":[67,87,65,53],
    "John":[56,78,65,64]
}

# Now, create DataFrame and assign index name as subject names
df = pd.DataFrame(d,index=["Maths","Physics","Chemistry","English"])

# Printing  the DataFrame
print("DataFrame is:")
print(df)

# Selecting a row value, 
# where column name is "Harry"
# and it's value is 66
print(df.loc[df['Harry']==66],"\n")

# Selecting a row value, 
# where column name is "Peter" 
# and it's value is 70
print(df.loc[df['Peter']==70],"\n")

Output:

DataFrame is:
           Peter  Harry  Tom  John
Maths         65     45   67    56
Physics       70     56   87    78
Chemistry     70     66   65    65
English       75     66   53    64
           Peter  Harry  Tom  John
Chemistry     70     66   65    65
English       75     66   53    64 

           Peter  Harry  Tom  John
Physics       70     56   87    78
Chemistry     70     66   65    65 

Example 2:

# Importing pandas package
import pandas as pd

# Creating DataFrame
df = pd.DataFrame({
    'Name': ['Alvin', 'Alex', 'Peter'],
    'Age': [21, 25, 30],
    'City':['New York', 'Washington', 'California']
})

# Printing the DataFrame
print("DataFrame is:")
print(df)

# Printing row, where
# Column name is "Name", and Value is "Peter"
print("\nResult:")
print(df.loc[df['Name'] == 'Peter'])

Output:

DataFrame is:
    Name  Age        City
0  Alvin   21    New York
1   Alex   25  Washington
2  Peter   30  California

Result:
    Name  Age        City
2  Peter   30  California

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to change the order of DataFrame columns?... >>
<< How to rename columns in Pandas DataFrame?...