Class 12 Informatics Practices Worksheet: Accessing Rows and Columns in DataFrames
Part A: Fill in the Blanks
- To work with DataFrames in Python, we use the __________ library.
- The method used to access a specific column in a DataFrame is __________.
- To access a row by its index, you use __________ indexing with the
iloc
method. - The method to access data using labels is __________.
- To get the first few rows of a DataFrame, you use the __________ method.
Part B: True or False
- The
df.loc[]
method is used to access data by integer location. (True / False) - You can access a column in a DataFrame using
df['column_name']
. (True / False) - The
df.iloc[]
method can be used to access data by label. (True / False) - DataFrame columns can be accessed using a dot notation like
df.column_name
. (True / False) - The
df.head()
method displays the last few rows of the DataFrame. (True / False)
Part C: Short Answer Questions
- How do you access the third row of a DataFrame using integer-based indexing?
- Write the code to select the column named
Age
from a DataFramedf
. - Explain the difference between
df.loc[]
anddf.iloc[]
methods. - How can you select multiple columns from a DataFrame? Provide an example.
- Write the code to access rows 5 to 10 (inclusive) of a DataFrame
df
using integer-based indexing.
Part D: Practical Exercises
Given the following DataFrame:
pythonimport pandas as pd data = { 'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'], 'Age': [24, 27, 22, 32, 29], 'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix'] } df = pd.DataFrame(data)
Perform the following tasks:
- Access the column
City
. - Select the row with index 2.
- Retrieve the value of
Age
for the person with index 3. - Display the first 3 rows of the DataFrame.
- Access the column
Create a DataFrame with the following data:
Name Subject Marks John Math 85 Alice Science 92 Bob English 78 Carol History 88 Write the code to:
- Select the
Subject
column. - Get the rows where
Marks
are greater than 80. - Select the
Name
andMarks
columns for the first 2 rows.
- Select the
Given a DataFrame
df
with the following structure:import pandas as pd data = { 'Product': ['A', 'B', 'C', 'D', 'E'], 'Price': [100, 150, 200, 250, 300], 'Stock': [50, 30, 20, 10, 5] } df = pd.DataFrame(data)
Write code to:
- Access the
Price
column. - Retrieve the last 2 rows of the DataFrame.
- Access the
Stock
value for the product with index 1.
- Access the
Part E: Code Correction
Examine the following code snippets and correct any mistakes related to accessing rows and columns in DataFrames. Rewrite the correct code.
import pandas as pd data = { 'Name': ['Anna', 'Ben', 'Charlie'], 'Age': [22, 23, 25] } df = pd.DataFrame(data) print(df[1]) # Incorrect
import pandas as pd data = { 'Product': ['X', 'Y', 'Z'], 'Price': [10, 20, 30] } df = pd.DataFrame(data) print(df.loc[1, 'Price']) # Correct print(df.iloc['Product']) # Incorrect
0 Comments
Please do note create link post in comment section