开始使用免费开始使用

设置与移除索引

pandas 允许您将某些列指定为索引(index)。这样在取子集时代码更简洁,在某些情况下查找也更高效。

在本章中,您将使用 temperatures,这是一个包含全球各城市平均气温的 DataFrame。pandas 已以 pd 导入。

本练习是课程的一部分

使用 pandas 进行数据处理

查看课程

练习说明

  • 查看 temperatures
  • temperatures 的索引设为 "city",并保存为 temperatures_ind
  • 查看 temperatures_ind。它与 temperatures 有何不同?
  • 重置 temperatures_ind 的索引,并保留其索引内容。
  • 重置 temperatures_ind 的索引,并丢弃其索引内容。

交互式实操练习

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

# Look at temperatures
print(____)

# Set the index of temperatures to city
temperatures_ind = ____

# Look at temperatures_ind
print(____)

# Reset the temperatures_ind index, keeping its contents
print(____)

# Reset the temperatures_ind index, dropping its contents
print(____)
编辑并运行代码