loc and iloc (1)
With loc
and iloc
you can do practically any data selection operation on DataFrames you can think of. loc
is label-based, which means that you have to specify rows and columns based on their row and column labels. iloc
is integer index based, so you have to specify rows and columns by their integer index like you did in the previous exercise.
Try out the following commands to experiment with loc
and iloc
to select observations. Each pair of commands here gives the same result.
cars.loc['RU']
cars.iloc[4]
cars.loc[['RU']]
cars.iloc[[4]]
cars.loc[['RU', 'AUS']]
cars.iloc[[4, 1]]
As before, code is included that imports the cars data as a Pandas DataFrame.
This is a part of the course
“Intermediate Python”
Exercise instructions
- Use
loc
oriloc
to select the observation corresponding to Japan as a Series. The label of this row isJPN
, the index is2
. Make sure to print the resulting Series. - Use
loc
oriloc
to select the observations for Australia and Egypt as a DataFrame. You can find out about the labels/indexes of these rows by inspectingcars
. Make sure to print the resulting DataFrame.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
# Print out observation for Japan
# Print out observations for Australia and Egypt
This exercise is part of the course
Intermediate Python
Level up your data science skills by creating visualizations using Matplotlib and manipulating DataFrames with pandas.
Learn about the dictionary, an alternative to the Python list, and the pandas DataFrame, the de facto standard to work with tabular data in Python. You will get hands-on practice with creating and manipulating datasets, and you’ll learn how to access the information you need from these data structures.
Exercise 1: Dictionaries, Part 1Exercise 2: Motivation for dictionariesExercise 3: Create dictionaryExercise 4: Access dictionaryExercise 5: Dictionaries, Part 2Exercise 6: Dictionary Manipulation (1)Exercise 7: Dictionary Manipulation (2)Exercise 8: DictionariceptionExercise 9: Pandas, Part 1Exercise 10: Dictionary to DataFrame (1)Exercise 11: Dictionary to DataFrame (2)Exercise 12: CSV to DataFrame (1)Exercise 13: CSV to DataFrame (2)Exercise 14: Pandas, Part 2Exercise 15: Square Brackets (1)Exercise 16: Square Brackets (2)Exercise 17: loc and iloc (1)Exercise 18: loc and iloc (2)Exercise 19: loc and iloc (3)What is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.