Pandasで時系列データを集計しています。
ある条件が発生してから次の条件発生までの範囲の最大値を求めたいのですが、applyを使わずに簡潔に記載する方法はないでしょうか?
実現したいこと
下の表で Cond=True の場合、現在のPriceを代入
Cond=Falseの場合、「以前のCond=TrueのPrice」と「現在のPrice」のうち大きい方を代入
例:行1 Cond=True → Price=450(現在のPrice)
行2 Cond=False → Price=450(前の行が大きい)
行3 Cond=False → Price=450(2つ前の行が大きい)
python
1iimport pandas as pd 2import numpy as np 3df = pd.DataFrame({'Price': [350, 450, 300, 250, 400, 550, 600 ], 4 'Cond': [False, True, False, False, False, True, False]})
python
1 Price Cond 20 350 False 31 450 True 42 300 False 53 250 False 64 400 False 75 550 True 86 600 False
求めたい結果と現状のapplyでの処理は以下です。
簡潔化と処理速度向上を計りたいです。rolling()でwindowの数値を変えればできるかと試したのですが、うまくいかず、良い方法があれば教えていただけないでしょうか。
どうぞよろしくお願いいたします。
python
1 Price Cond bar_index pvid New 20 350 False 0 0 350.0 31 450 True 1 1 450.0 42 300 False 2 1 450.0 53 250 False 3 1 450.0 64 400 False 4 1 450.0 75 550 True 5 5 550.0 86 600 False 6 5 600.0 9--------------------------------------------------------- 10df['bar_index']=df.index 11df.loc[df['Cond']==True, 'pvid'] = df['bar_index'] 12df['pvid'] = df['pvid'].fillna(method='ffill').fillna(0).astype(int) 13 14def set_pivot(x): 15 if x['Cond']: 16 df.loc[x['bar_index'], 'New'] = df.loc[x['bar_index'], 'Price'] 17 elif x['Cond']==False: 18 df.loc[x['bar_index'], 'New'] = df.loc[x['pvid']:x['bar_index'], 'Price'].max() 19 20df.apply(set_pivot, axis=1)

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/02/27 13:32