練習4-Apply函數(shù)
探索1960 - 2014 美國犯罪數(shù)據(jù)
步驟1 導(dǎo)入必要的庫
運行以下代碼
import pandas as pd
import numpy as np
步驟2 從以下地址導(dǎo)入數(shù)據(jù)集
運行以下代碼
#?本地對應(yīng)的"US_Crime_Rates_1960_2014.csv"路徑
path4 = 'D:/hailong/hailong_download/pandas_exercise/exercise_data/US_Crime_Rates_1960_2014.csv'?
步驟3 將數(shù)據(jù)框命名為crime
運行以下代碼
crime=pd.read_csv(path4)
crime.head()
步驟4 每一列(column)的數(shù)據(jù)類型是什么樣的粹排?
運行以下代碼
crime.info()
注意到了嗎,此時Year的數(shù)據(jù)類型為?int64涩澡,但是pandas有一個不同的數(shù)據(jù)類型去處理時間序列(time series)顽耳,我們現(xiàn)在來看看。
步驟5 將Year的數(shù)據(jù)類型轉(zhuǎn)換為?datetime64
運行以下代碼
crime.Year = pd.to_datetime(crime.Year,format = '%Y')
crime.info()
步驟6 將列Year設(shè)置為數(shù)據(jù)框的索引
運行以下代碼
crime = crime.set_index('Year',drop = True)
crime.head()
步驟7 刪除名為Total的列
運行以下代碼
del crime['Total']
crime.head()
crime.resample('10AS').sum()
步驟8 按照Year對數(shù)據(jù)框進行分組并求和
*注意Population這一列妙同,若直接對其求和射富,是不正確的**
運行以下代碼
# 更多關(guān)于 .resample 的介紹
# (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html)
# 更多關(guān)于 Offset Aliases的介紹?
# (http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases)
crimes = crime.resample('10AS').sum()
population = crime['Population'].resample('10AS').max()
crimes['Population'] = population
crimes
步驟9 何時是美國歷史上生存最危險的年代?
運行以下代碼
crime.idxmax(0)