在透视表上进行计算
透视表里本身就是汇总统计,但这只是迈向洞见的第一步。很多时候,您还需要在其基础上继续计算。一个常见做法是找出出现最高值或最低值的行或列。
回顾第 1 章,您可以在方括号内使用逻辑条件,轻松对子序列或 DataFrame 进行子集选择,找出感兴趣的行。例如:series[series > value]。
pandas 已以 pd 导入,且 DataFrame temp_by_country_city_vs_year 可用。
该 DataFrame 的 .head() 如下所示,仅展示了部分年份列:
| country | city | 2000 | 2001 | 2002 | … | 2013 |
|---|---|---|---|---|---|---|
| Afghanistan | Kabul | 15.823 | 15.848 | 15.715 | … | 16.206 |
| Angola | Luanda | 24.410 | 24.427 | 24.791 | … | 24.554 |
| Australia | Melbourne | 14.320 | 14.180 | 14.076 | … | 14.742 |
| Sydney | 17.567 | 17.854 | 17.734 | … | 18.090 | |
| Bangladesh | span translate="no">Dhaka | 25.905 | 25.931 | 26.095 | … | 26.587 |
本练习是课程的一部分
使用 pandas 进行数据处理
练习说明
- 计算各年份的平均气温,并赋值给
mean_temp_by_year。 - 过滤
mean_temp_by_year,找出平均气温最高的年份。 - 计算各城市(跨列)的平均气温,并赋值给
mean_temp_by_city。 - 过滤
mean_temp_by_city,找出平均气温最低的城市。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Get the worldwide mean temp by year
mean_temp_by_year = temp_by_country_city_vs_year.____
# Filter for the year that had the highest mean temp
print(mean_temp_by_year[____])
# Get the mean temp by city
mean_temp_by_city = temp_by_country_city_vs_year.____
# Filter for the city that had the lowest mean temp
print(mean_temp_by_city[____])