第七章:數據規整化

說明:本文章爲Python數據處理學習日誌,記錄內容爲實現書本內容時遇到的錯誤以及一些與書本不一致的地方,一些簡單操作則不再贅述。日誌主要內容來自書本《利用Python進行數據分析》,Wes McKinney著,機械工業出版社。

這篇博文主要是爲了補全python處理數據系列,基本上本章沒有太多的問題,主要就是P202的數據作者並沒有給出,手動編輯csv太麻煩,接下來介紹如何用代碼將macrodata.csv轉化成可用的數據。

data = pd.read_csv('macrodata.csv')

temp_data = DataFrame(data,columns=['year','quarter','realgdp','infl','unemp'])

temp_data[:2]
Out[105]: 
     year  quarter   realgdp  infl  unemp
0  1959.0      1.0  2710.349  0.00    5.8
1  1959.0      2.0  2778.801  2.34    5.1

for i in range(len(temp_data.index)):
    if int(temp_data[i:i+1].quarter) == 1:
        temp_data.loc[i,'date'] = datetime(temp_data[i:i+1].year,3,31)
    elif int(temp_data[i:i+1].quarter) ==2:
        temp_data.loc[i,'date'] = datetime(temp_data[i:i+1].year,6,30)
    elif int(temp_data[i:i+1].quarter) ==3:
        temp_data.loc[i,'date'] = datetime(temp_data[i:i+1].year,9,30)
    elif int(temp_data[i:i+1].quarter) ==4:
        temp_data.loc[i,'date'] = datetime(temp_data[i:i+1].year,12,31)


temp_data[:2]
Out[107]: 
     year  quarter   realgdp  infl  unemp       date
0  1959.0      1.0  2710.349  0.00    5.8 1959-03-31
1  1959.0      2.0  2778.801  2.34    5.1 1959-06-30

'''這一步如果看不清楚,可以拆開來一步一步看效果'''
temp_data = temp_data.drop(['year','quarter'],1).set_index('date').stack()

temp_data[:10]
Out[109]: 
date               
1959-03-31  realgdp    2710.349
            infl          0.000
            unemp         5.800
1959-06-30  realgdp    2778.801
            infl          2.340
            unemp         5.100
1959-09-30  realgdp    2775.488
            infl          2.740
            unemp         5.300
1959-12-31  realgdp    2785.204
dtype: float64

temp_data.to_csv('new.csv')

ldata = pd.read_csv('new.csv',names=['date','item','value'])

ldata[:10]
Out[112]: 
         date     item     value
0  1959-03-31  realgdp  2710.349
1  1959-03-31     infl     0.000
2  1959-03-31    unemp     5.800
3  1959-06-30  realgdp  2778.801
4  1959-06-30     infl     2.340
5  1959-06-30    unemp     5.100
6  1959-09-30  realgdp  2775.488
7  1959-09-30     infl     2.740
8  1959-09-30    unemp     5.300
9  1959-12-31  realgdp  2785.204
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章