数据分析Pandas练习题四:Apply函数

import numpy as np
import pandas as pd

path = '../../data/exercise_data/US_Crime_Rates_1960_2014.csv'

# 展示被省略的列
pd.set_option('display.max_columns', 12)

crime = pd.read_csv(path)

# print(crime.head())

# 每一列(column)的数据类型是什么样的?
# print(crime.info())

# 将Year的数据类型转换为 datetime64
crime.Year = pd.to_datetime(crime.Year, format='%Y')
# print(crime.info())

# 将列Year设置为数据框的索引
crime = crime.set_index('Year', drop=True)
# print(crime.head())

# 删除名为Total的列
del crime['Total']
# print(crime.head())

# 按照Year对数据框进行分组并求和
# print(crime.groupby('Year').sum())

# 更多关于 .resample 的介绍
# (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html)
# 更多关于 Offset Aliases的介绍
# (http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases)
# 运行以下代码
# resample a time series per decades
crimes = crime.resample('10AS').sum()
# 用resample去得到“Population”列的最大值
population = crime['Population'].resample('10AS').max()
# 更新 "Population"
crimes['Population'] = population
# print(crimes)

# 何时是美国历史上生存最危险的年代
print(crime.idxmax(0))

你可能感兴趣的:(Python从小白变小黑,pandas,python,数据分析)