第九章:數據聚合與分組運算

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

3、分組級運算和轉換

P285示例

pct_change()

Signature: DataFrame.pct_change(self, periods=1, fill_method=’pad’, limit=None, freq=None, **kwargs)

Docstring Percent change over given number of periods.

Parameters
periods : int, default 1
Periods to shift for forming percent change
fill_method : str, default ‘pad’
How to handle NAs before computing percent changes
limit : int, default None
The number of consecutive NAs to fill before stopping
freq : DateOffset, timedelta, or offset alias string, optional
Increment to use from time series API (e.g. ‘M’ or BDay())

Returns
chg : NDFrame

這個函數運算方法如下:

test = DataFrame([1,2,4,4,5])

test['pct_change'] = test.pct_change()

test
Out[45]: 
   0  pct_change
0  1         NaN  #第一個數據沒有
1  2        1.00  #(2-1)/1=1
2  4        1.00  #(4-2)/2=1
3  4        0.00  #(4-4)/4=0
4  5        0.25  #(5-4)/4=0

test['pct_change'] = test.pct_change(periods=2)

test
Out[47]: 
   0  pct_change
0  1         NaN
1  2         NaN  #前兩個沒有
2  4        3.00  #(4-1)/1=3
3  4        1.00  #(4-2)/2=1
4  5        0.25  #(5-4)/4=0.25
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章