Dictionary to DataFrame (2)
The Python code that solves the previous exercise is included in the script. Have you noticed that the row labels (i.e. the labels for the different observations) were automatically set to integers from 0 up to 6?
To solve this a list row_labels
has been created. You can use it to specify the row labels of the cars
DataFrame. You do this by setting the index
attribute of cars
, that you can access as cars.index
.
This exercise is part of the course
Intermediate Python
Exercise instructions
- Hit Run Code to see that, indeed, the row labels are not correctly set.
- Specify the row labels by setting
cars.index
equal torow_labels
. - Print out
cars
again and check if the row labels are correct this time.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
import pandas as pd
# Build cars DataFrame
names = ['United States', 'Australia', 'Japan', 'India', 'Russia', 'Morocco', 'Egypt']
dr = [True, False, False, False, True, True, True]
cpc = [809, 731, 588, 18, 200, 70, 45]
cars_dict = { 'country':names, 'drives_right':dr, 'cars_per_cap':cpc }
cars = pd.DataFrame(cars_dict)
print(cars)
# Definition of row_labels
row_labels = ['US', 'AUS', 'JPN', 'IN', 'RU', 'MOR', 'EG']
# Specify row labels of cars
# Print cars again