Slicing DataFrame with .loc in Pandas
Pandas: Advanced Indexing and Slicing Exercise-12 with Solution
Slicing with loc:
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.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics