Data selection and indexing are among the most important skills in Pandas. They allow you to retrieve specific rows, columns, or subsets of data efficiently from a DataFrame. Pandas provides several powerful methods for data selection, including square bracket notation ([]), loc[], iloc[], Boolean indexing, and conditional filtering. Mastering these techniques is essential for cleaning, analyzing, and transforming datasets in real-world data analysis projects. Pandas Data Selection and Indexing practice questions with solutions help to understand the concepts.
1. Python Program to Select a Single Column from a DataFrame
Problem Statement
Write a Python program to select and display the Name column from a Pandas DataFrame.
Python Solution
import pandas as pd
data = {
"Name": ["Rahul", "Aman", "Priya", "Sneha"],
"Age": [20, 21, 19, 22],
"Marks": [85, 90, 78, 88]
}
df = pd.DataFrame(data)
print(df["Name"])
Sample Output
0 Rahul
1 Aman
2 Priya
3 Sneha
Name: Name, dtype: object
Explanation
Selecting a single column using square brackets returns a Pandas Series containing all values from that column.
Concepts Covered
- Column Selection
- Series
- Square Bracket Notation
2. Python Program to Select Multiple Columns
Problem Statement
Write a Python program to display the Name and Marks columns from a DataFrame.
Python Solution
import pandas as pd
data = {
"Name": ["Rahul", "Aman", "Priya", "Sneha"],
"Age": [20, 21, 19, 22],
"Marks": [85, 90, 78, 88]
}
df = pd.DataFrame(data)
print(df[["Name", "Marks"]])
Sample Output
Name Marks
0 Rahul 85
1 Aman 90
2 Priya 78
3 Sneha 88
Explanation
To retrieve multiple columns, pass a list of column names inside double square brackets.
Concepts Covered
- Multiple Column Selection
- DataFrame Columns
- List Indexing
3. Python Program to Select a Single Row Using loc[]
Problem Statement
Write a Python program to display the third row of a DataFrame using loc[].
Python Solution
import pandas as pd
data = {
"Name": ["Rahul", "Aman", "Priya", "Sneha"],
"Age": [20, 21, 19, 22],
"Marks": [85, 90, 78, 88]
}
df = pd.DataFrame(data)
print(df.loc[2])
Sample Output
Name Priya
Age 19
Marks 78
Name: 2, dtype: object
Explanation
The loc[] method selects rows using index labels. Since the default index starts from 0, index 2 represents the third row.
Concepts Covered
loc[]- Label-Based Indexing
- Row Selection
4. Python Program to Select Multiple Rows Using loc[]
Problem Statement
Write a Python program to display the first three rows using loc[].
Python Solution
import pandas as pd
data = {
"Name": ["Rahul", "Aman", "Priya", "Sneha", "Rohit"],
"Marks": [85, 90, 78, 88, 95]
}
df = pd.DataFrame(data)
print(df.loc[0:2])
Sample Output
Name Marks
0 Rahul 85
1 Aman 90
2 Priya 78
Explanation
Unlike Python slicing, loc[] includes both the starting and ending index labels.
Concepts Covered
loc[]- Row Range Selection
- Label-Based Slicing
5. Python Program to Select a Row Using iloc[]
Problem Statement
Write a Python program to retrieve the fourth row using iloc[].
Python Solution
import pandas as pd
data = {
"Name": ["Rahul", "Aman", "Priya", "Sneha"],
"Age": [20, 21, 19, 22],
"Marks": [85, 90, 78, 88]
}
df = pd.DataFrame(data)
print(df.iloc[3])
Sample Output
Name Sneha
Age 22
Marks 88
Name: 3, dtype: object
Explanation
The iloc[] method selects rows using integer positions rather than index labels.
Concepts Covered
iloc[]- Integer Position
- Row Selection
6. Python Program to Select Multiple Rows Using iloc[]
Problem Statement
Write a Python program to display the first four rows of a DataFrame using iloc[].
Python Solution
import pandas as pd
data = {
"Name": ["Rahul", "Aman", "Priya", "Sneha", "Rohit", "Anjali"],
"Age": [20, 21, 19, 22, 23, 20],
"Marks": [85, 90, 78, 88, 95, 91]
}
df = pd.DataFrame(data)
print(df.iloc[0:4])
Sample Output
Name Age Marks
0 Rahul 20 85
1 Aman 21 90
2 Priya 19 78
3 Sneha 22 88
Explanation
The iloc[] method uses integer positions for slicing. Like Python lists, the ending position is excluded.
Concepts Covered
iloc[]- Row Slicing
- Integer Indexing
7. Python Program to Select Specific Rows and Columns Using loc[]
Problem Statement
Write a Python program to display only the Name and Marks columns for the first three rows using loc[].
Python Solution
import pandas as pd
data = {
"Name": ["Rahul", "Aman", "Priya", "Sneha"],
"Age": [20, 21, 19, 22],
"Marks": [85, 90, 78, 88]
}
df = pd.DataFrame(data)
print(df.loc[0:2, ["Name", "Marks"]])
Sample Output
Name Marks
0 Rahul 85
1 Aman 90
2 Priya 78
Explanation
The loc[] method allows simultaneous selection of rows and columns using labels.
Concepts Covered
loc[]- Row and Column Selection
- Label Indexing
8. Python Program to Select Specific Rows and Columns Using iloc[]
Problem Statement
Write a Python program to display the first three rows and the first two columns using iloc[].
Python Solution
import pandas as pd
data = {
"Name": ["Rahul", "Aman", "Priya", "Sneha"],
"Age": [20, 21, 19, 22],
"Marks": [85, 90, 78, 88]
}
df = pd.DataFrame(data)
print(df.iloc[0:3, 0:2])
Sample Output
Name Age
0 Rahul 20
1 Aman 21
2 Priya 19
Explanation
The iloc[] method selects both rows and columns using integer positions.
Concepts Covered
iloc[]- Row and Column Selection
- Integer Position
9. Python Program to Select Rows Based on a Condition
Problem Statement
Write a Python program to display students whose marks are greater than 85.
Python Solution
import pandas as pd
data = {
"Name": ["Rahul", "Aman", "Priya", "Sneha", "Rohit"],
"Marks": [85, 90, 78, 88, 95]
}
df = pd.DataFrame(data)
print(df[df["Marks"] > 85])
Sample Output
Name Marks
1 Aman 90
3 Sneha 88
4 Rohit 95
Explanation
Boolean indexing filters rows that satisfy the specified condition.
Concepts Covered
- Boolean Indexing
- Conditional Selection
- Filtering Data
10. Python Program to Select Rows Using Multiple Conditions
Problem Statement
Write a Python program to display students whose Age is greater than 20 and Marks are greater than or equal to 90.
Python Solution
import pandas as pd
data = {
"Name": ["Rahul", "Aman", "Priya", "Sneha", "Rohit"],
"Age": [20, 21, 19, 22, 23],
"Marks": [85, 90, 78, 88, 95]
}
df = pd.DataFrame(data)
result = df[(df["Age"] > 20) & (df["Marks"] >= 90)]
print(result)
Sample Output
Name Age Marks
1 Aman 21 90
4 Rohit 23 95
Explanation
Multiple conditions can be combined using:
&→ AND|→ OR
Each condition must be enclosed within parentheses.
Concepts Covered
- Boolean Operators
- AND Operator
- Conditional Filtering
- Multiple Conditions
11. Python Program to Select Rows Using the OR Operator
Problem Statement
Write a Python program to display students whose Marks are greater than or equal to 90 or Age is less than 20.
Python Solution
import pandas as pd
data = {
"Name": ["Rahul", "Aman", "Priya", "Sneha", "Rohit"],
"Age": [20, 21, 19, 22, 23],
"Marks": [85, 90, 78, 88, 95]
}
df = pd.DataFrame(data)
result = df[(df["Marks"] >= 90) | (df["Age"] < 20)]
print(result)
Sample Output
Name Age Marks
1 Aman 21 90
2 Priya 19 78
4 Rohit 23 95
Explanation
The | (OR) operator returns rows that satisfy at least one of the specified conditions.
Concepts Covered
- OR Operator
- Boolean Indexing
- Conditional Filtering
12. Python Program to Select Rows Using isin()
Problem Statement
Write a Python program to display students whose names are Rahul or Sneha.
Python Solution
import pandas as pd
data = {
"Name": ["Rahul", "Aman", "Priya", "Sneha", "Rohit"],
"Marks": [85, 90, 78, 88, 95]
}
df = pd.DataFrame(data)
print(df[df["Name"].isin(["Rahul", "Sneha"])])
Sample Output
Name Marks
0 Rahul 85
3 Sneha 88
Explanation
The isin() function checks whether each value belongs to the specified list and returns matching rows.
Concepts Covered
isin()- Membership Filtering
- Boolean Selection
13. Python Program to Select Rows with Missing Values
Problem Statement
Write a Python program to display all rows containing missing values.
Python Solution
import pandas as pd
import numpy as np
data = {
"Name": ["Rahul", "Aman", "Priya", "Sneha"],
"Marks": [85, np.nan, 78, np.nan]
}
df = pd.DataFrame(data)
print(df[df["Marks"].isnull()])
Sample Output
Name Marks
1 Aman NaN
3 Sneha NaN
Explanation
The isnull() function identifies missing values. It is commonly used during data cleaning.
Concepts Covered
isnull()- Missing Values
- Data Filtering
14. Python Program to Select Rows Without Missing Values
Problem Statement
Write a Python program to display only rows that do not contain missing values in the Marks column.
Python Solution
import pandas as pd
import numpy as np
data = {
"Name": ["Rahul", "Aman", "Priya", "Sneha"],
"Marks": [85, np.nan, 78, 92]
}
df = pd.DataFrame(data)
print(df[df["Marks"].notnull()])
Sample Output
Name Marks
0 Rahul 85.0
2 Priya 78.0
3 Sneha 92.0
Explanation
The notnull() function returns only those rows where the selected column contains valid (non-missing) values.
Concepts Covered
notnull()- Data Cleaning
- Missing Values
15. Python Program to Select Rows Using query()
Problem Statement
Write a Python program to select students whose marks are greater than 80 using the query() function.
Python Solution
import pandas as pd
data = {
"Name": ["Rahul", "Aman", "Priya", "Sneha"],
"Marks": [85, 90, 78, 88]
}
df = pd.DataFrame(data)
result = df.query("Marks > 80")
print(result)
Sample Output
Name Marks
0 Rahul 85
1 Aman 90
3 Sneha 88
Explanation
The query() function filters rows using a readable string expression instead of Boolean indexing.
Concepts Covered
query()- Conditional Filtering
- Data Selection
16. Python Program to Select Unique Values from a Column
Problem Statement
Write a Python program to display all unique values present in the Course column of a DataFrame.
Python Solution
import pandas as pd
data = {
"Student": ["Rahul", "Aman", "Priya", "Sneha", "Rohit"],
"Course": [
"Python",
"Java",
"Python",
"Data Science",
"Java"
]
}
df = pd.DataFrame(data)
print(df["Course"].unique())
Sample Output
['Python' 'Java' 'Data Science']
Explanation
The unique() function returns only the distinct values from a column. It is useful for identifying categories, removing duplicates, and exploring categorical data.
Concepts Covered
unique()- Distinct Values
- Data Exploration
17. Python Program to Count Unique Values in a Column
Problem Statement
Write a Python program to count how many unique values exist in the Course column.
Python Solution
import pandas as pd
data = {
"Student": ["Rahul", "Aman", "Priya", "Sneha", "Rohit"],
"Course": [
"Python",
"Java",
"Python",
"Data Science",
"Java"
]
}
df = pd.DataFrame(data)
print("Total Unique Courses:", df["Course"].nunique())
Sample Output
Total Unique Courses: 3
Explanation
The nunique() function counts the number of distinct values present in a column without displaying them.
Concepts Covered
nunique()- Unique Count
- Data Analysis
Chapter Summary
In this chapter, you learned how to perform data selection and indexing in Pandas using different techniques. You explored selecting rows and columns with square brackets, loc[], and iloc[], filtering data with Boolean conditions, using logical operators (& and |), selecting values with isin(), identifying missing values using isnull() and notnull(), filtering data with query(), and retrieving unique values using unique() and nunique(). These operations are fundamental for efficient data analysis and real-world data manipulation.
Key Takeaways
- Use square brackets (
[]) to select columns from a DataFrame. loc[]performs label-based indexing.iloc[]performs integer position-based indexing.- Boolean indexing is useful for filtering rows based on conditions.
- Combine multiple conditions using
&(AND) and|(OR). - Use
isin()to filter rows that match multiple values. isnull()andnotnull()help identify missing data.query()provides a clean and readable way to filter data.unique()returns distinct values, whilenunique()counts them.
Frequently Asked Questions (FAQs)
1. What is data selection in Pandas?
Data selection is the process of retrieving specific rows, columns, or subsets of data from a DataFrame for analysis.
2. What is the difference between loc[] and iloc[]?
loc[]selects data using row or column labels.iloc[]selects data using integer positions.
3. How do you filter rows based on a condition?
Use Boolean indexing.
filtered_df = df[df["Marks"] > 80]
print(filtered_df)
4. What does the isin() function do?
The isin() function filters rows by checking whether values exist in a specified list.
df[df["Course"].isin(["Python", "Java"])]
5. How do you find missing values in Pandas?
Use the isnull() function.
df.isnull()
6. What is the purpose of the query() function?
The query() function filters DataFrame rows using a readable string expression instead of Boolean indexing.
df.query("Marks >= 85")
7. What is the difference between unique() and nunique()?
unique()returns all distinct values.nunique()returns the total number of distinct values.
8. Why is indexing important in Pandas?
Indexing enables fast data retrieval, filtering, slicing, and analysis, making it one of the most essential features of the Pandas library for data manipulation.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
