Slicing DataFrame with .loc in Pandas
12. .loc Slicing Based on Row and Column Labels
Write a Pandas program that uses .loc to slice DataFrame based on row and column labels.
Sample Solution :
Python Code :
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
'X': [1, 6, 8, 3, 7],
'Y': [5, 2, 9, 4, 1],
'Z': [7, 8, 9, 1, 2]
})
# Slice DataFrame using .loc
result = df.loc[1:3, ['X', 'Z']]
print(result)
Output:
X Z 1 6 8 2 8 9 3 3 1
Explanation:
- Import pandas library.
- Create a DataFrame.
- Use .loc to slice rows from index 1 to 3 and select columns 'X' and 'Z'.
- Print the results.
For more Practice: Solve these Related Problems:
- Write a Pandas program to slice a DataFrame using .loc by specifying both row and column label ranges.
- Write a Pandas program to extract a block of data from a DataFrame using .loc with label-based slicing.
- Write a Pandas program to select a subset of rows and columns using .loc and then compute a statistical summary of the result.
- Write a Pandas program to use .loc to slice a DataFrame and then plot the selected data using a line chart.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Setting values with .loc in Pandas DataFrame.
Next: Advanced Boolean indexing in Pandas DataFrame.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.