0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

cumprodとcummaxについて

Posted at

#1 目的
cumprodとcummaxの使い方例を説明します。

#2 内容

cumprod ・・・ 配列の全要素について累積積を計算します。
cummax ・・・ 配列の全要素から最大値を取り出します。

test.py
import numpy as np
import pandas as pd


dat = [
    ['2019-07-01',10],
    ['2019-07-02',12],
    ['2019-07-03',8],
    ['2019-07-04',14],
    ['2019-07-05',7],
    ['2019-07-08',3]
]
df0 = pd.DataFrame(dat,columns=["A","B"])

print(df0)

df1=df0['B'].pct_change()
df2=(1 + df1)
df3=(1 + df1).cumprod() #0番目からi番目の要素までの累積積を算出します。
df4=(1 + df1).cummax()  #0番目からi番目の要素の中で最大値を取り出します。
print(df1)
print(df2)
print(df3)
print(df4)
<df0:基本データ>
            A   B
0  2019-07-01  10
1  2019-07-02  12
2  2019-07-03   8
3  2019-07-04  14
4  2019-07-05   7
5  2019-07-08   3

df1: (df0['B']のi番目とi-1番目の変化率を計算する)
0         NaN
1    0.200000
2   -0.333333
3    0.750000
4   -0.500000
5   -0.571429
Name: B, dtype: float64

df2: (df1+1を計算する)
0         NaN
1    1.200000
2    0.666667
3    1.750000
4    0.500000
5    0.428571
Name: B, dtype: float64

df2: (cumprod() 累積積を計算する)

0    NaN
1    1.2
2    0.8  (=1.2×0.666667)
3    1.4   (=1.2×0.666667×1.75)
4    0.7   (=1.2×0.666667×1.75×0.5)
5    0.3   (=1.2×0.666667×1.75×0.5×0.428)
Name: B, dtype: float64

df3: (cummax() 要素の中から最大値を取り出す。)

0     NaN
1    1.20   (df2:要素1から要素1までの中での最大値)
2    1.20   (df2:要素1から要素2までの中での最大値)
3    1.75   (df2:要素1から要素3までの中での最大値)
4    1.75   (df2:要素1から要素4までの中での最大値)
5    1.75   (df2:要素1から要素5までの中での最大値)
Name: B, dtype: float64
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?