Indexing with .loc in Pandas DataFrame
7. Indexing with .loc
Write a Pandas program that uses .loc for indexing.
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]
})
# Indexing using .loc
result = df.loc[1]
print(result)
Output:
X 6 Y 2 Name: 1, dtype: int64
Explanation:
- Import pandas library.
- Create a DataFrame.
- Index the DataFrame using .loc.
- Print the results.
For more Practice: Solve these Related Problems:
- Write a Pandas program to use .loc to select rows based on label conditions from a DataFrame.
- Write a Pandas program to extract a subset of rows and columns using .loc with both label slicing and conditional filtering.
- Write a Pandas program to use .loc to select rows where the index label falls within a specified range.
- Write a Pandas program to update specific cell values in a DataFrame using .loc and then verify the changes.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Reset index of MultiIndex DataFrame in Pandas.
Next: Boolean indexing in Pandas DataFrame.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.