开始使用免费开始使用

州际人口流动

在视频中,您看到了一张州际迁移流的热力图,但信息较为杂乱。在本练习中,您将只查看中西部地区内部的流动。

一个名为 state_to_state 的 DataFrame 已载入,控制台显示了其前几行。请记住视频中的说明:行标签表示迁入的州,列名表示迁出的州。

列表 midwest_states 已定义,包含中西部各州的名称。(如果想查看包含哪些州,可以将其打印到控制台。)该 DataFrame 的列名和索引也使用州名,因此您将用 midwest_states 来提取本次热力图所需的列和行。

已按常用别名导入 pandasseaborn

本练习是课程的一部分

使用 Python 分析美国人口普查数据

查看课程

练习说明

  • 将数据框子集化,仅返回列名在州名列表中的列,以及索引在州名列表中的行。
  • 子集化可能改变了列与行的顺序。检查 midwest.index 是否等于 midwest.columns
  • 按行索引(axis = 0)和列名(axis = 1)对 DataFrame 排序。两处都使用 inplace = True
  • 基于 midwest 绘制热力图。将配色设置为黄-绿-蓝渐变,即 cmap="YlGnBu"

交互式实操练习

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

# Retain only rows and columns of Midwest states
midwest = state_to_state[____][state_to_state.index.isin(____)]

# Are rows and columns still in the same order?
print(____)

# Sort the rows (by index) and columns (by name)
midwest.sort_index(axis = ____, ____)
midwest.sort_index(axis = ____, ____)

# Create a heatmap of migration flows
____
plt.xticks(rotation=90)
plt.yticks(rotation=0)
plt.show()
编辑并运行代码