pandas.DataFrame.rolling
판다스에서는 롤링 윈도우 계산을 제공한다.
import pandas as pd
df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]})
df
B
0 0.0
1 1.0
2 2.0
3 NaN
4 4.0
window
관측치 2개의 window 길이를 사용한 롤링 합계는 다음과 같이 구현 가능하다.
df.rolling(2).sum()
B
0 NaN
1 1.0
2 3.0
3 NaN
4 NaN
window 범위가 2초인 롤링 합계는 다음과 같다.
df_time = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]},
index = [pd.Timestamp('20130101 09:00:00'),
pd.Timestamp('20130101 09:00:02'),
pd.Timestamp('20130101 09:00:03'),
pd.Timestamp('20130101 09:00:05'),
pd.Timestamp('20130101 09:00:06')])
df_time
B
2013-01-01 09:00:00 0.0
2013-01-01 09:00:02 1.0
2013-01-01 09:00:03 2.0
2013-01-01 09:00:05 NaN
2013-01-01 09:00:06 4.0
df_time.rolling('2s').sum()
B
2013-01-01 09:00:00 0.0
2013-01-01 09:00:02 1.0
2013-01-01 09:00:03 3.0
2013-01-01 09:00:05 NaN
2013-01-01 09:00:06 4.0
두 개의 관측치의 전방 window가 있는 롤링 합계는 다음과 같다.
indexer = pd.api.indexers.FixedForwardWindowIndexer(window_size=2)
df.rolling(window=indexer, min_periods=1).sum()
B
0 1.0
1 3.0
2 2.0
3 4.0
4 4.0
min_periods
window 길이가 관측치가 2개인 롤링 합계이지만 값을 계산하려면 최소 1개의 관측치만 필요하다.
df.rolling(2, min_periods=1).sum()
B
0 0.0
1 1.0
2 3.0
3 2.0
4 4.0
center
window 인덱스의 중앙에 결과가 할당된 롤링 합계이다.
df.rolling(3, min_periods=1, center=True).sum()
B
0 1.0
1 3.0
2 3.0
3 6.0
4 4.0
df.rolling(3, min_periods=1, center=False).sum()
B
0 0.0
1 1.0
2 3.0
3 3.0
4 6.0
step
window 길이가 관측치 2개, 값을 계산하기 위한 관측치 1개 이상, 단계가 2인 롤링 합계이다.
df.rolling(2, min_periods=1, step=2).sum()
B
0 0.0
2 3.0
4 4.0
win_type
Scipy의 'gaussian' window 유형을 사용하여 창 길이가 2인 롤링 합계이다. std는 집계 함수에 필요하다.
df.rolling(2, win_type='gaussian').sum(std=3)
B
0 NaN
1 0.986207
2 2.958621
3 NaN
4 NaN
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rolling.html
pandas.DataFrame.rolling — pandas 1.5.3 documentation
If 'right', the first point in the window is excluded from calculations. If 'left', the last point in the window is excluded from calculations. If 'both', the no points in the window are excluded from calculations. If 'neither', the first and last points i
pandas.pydata.org
'Python Library > Pandas' 카테고리의 다른 글
[Pandas] groupby (0) | 2023.03.30 |
---|---|
[Pandas] 데이터프레임 만들기 (0) | 2022.10.26 |
[Pandas] 타이타닉 생존자 분석 (0) | 2022.10.25 |
[Pandas] Iris (붓꽃) (0) | 2022.10.25 |
[Pandas] 시각화 (0) | 2022.10.23 |