开始使用免费开始使用

Dictionary 转 DataFrame(2)

解决上一个练习的 Python 代码已经包含在脚本中。您是否注意到,行标签(即不同观测的标签)被自动设置为了从 0 到 6 的整数?

为了解决这个问题,已经创建了一个列表 row_labels。您可以用它来指定 cars DataFrame 的行标签。方法是设置 carsindex 属性,您可以通过 cars.index 访问它。

本练习是课程的一部分

Python 中级

查看课程

练习说明

  • 点击 "Run Code",您会看到当前的行标签确实没有正确设置。
  • 通过将 cars.index 设为 row_labels 来指定行标签。
  • 再次打印 cars,检查这次行标签是否正确。

交互式实操练习

通过完成这段示例代码来试试这个练习。

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
编辑并运行代码