如何在 pandas MultiIndex 数据帧中有条件地重置滚动最大值的初始 value/row?
How to conditionally reset a rolling max's initial value/row in pandas MultiIndex dataframe?
我有一个多索引数据框。索引列为 Date
和 Symbol
。我想重置数据框开始评估每个 Symbol
的 rolling_max
of number
的行。我想基于包含 True
或 False
的列来执行此操作。如果 condition
在 Date
上是 True
,那么应该重置 rolling_max
并从这个 Date
计算最大值。如果 condition
是 False
,那么 rolling_max
应该有效 'normally' - 取今天和昨天的最大值 number
给定的 Symbol
。 condition
列与 number
列无关(它们不相互依赖)。这是预期的输出:
number condition rolling_max
Date Symbol
1990-01-01 A 29 False 29
1990-01-01 B 7 False 7
1990-01-02 A 13 True 13 # Reset rolling max for 'A'
1990-01-02 B 2 False 7
1990-01-03 A 11 False 13
1990-01-03 B 52 True 52 # Reset rolling max for 'B'
1990-01-04 A 30 False 30
1990-01-04 B 1 False 52
1990-01-05 A 19 True 19 # Reset rolling max for 'A'
1990-01-05 B 65 False 65
1990-01-06 A 17 False 19
1990-01-06 B 20 True 20 # Reset rolling max for 'B'
我该怎么做?
我能够解决这个问题。
df['rolling_max'] = df.groupby(['Symbol',df.groupby('Symbol')['condition'].cumsum()])['number'].cummax()
我有一个多索引数据框。索引列为 Date
和 Symbol
。我想重置数据框开始评估每个 Symbol
的 rolling_max
of number
的行。我想基于包含 True
或 False
的列来执行此操作。如果 condition
在 Date
上是 True
,那么应该重置 rolling_max
并从这个 Date
计算最大值。如果 condition
是 False
,那么 rolling_max
应该有效 'normally' - 取今天和昨天的最大值 number
给定的 Symbol
。 condition
列与 number
列无关(它们不相互依赖)。这是预期的输出:
number condition rolling_max
Date Symbol
1990-01-01 A 29 False 29
1990-01-01 B 7 False 7
1990-01-02 A 13 True 13 # Reset rolling max for 'A'
1990-01-02 B 2 False 7
1990-01-03 A 11 False 13
1990-01-03 B 52 True 52 # Reset rolling max for 'B'
1990-01-04 A 30 False 30
1990-01-04 B 1 False 52
1990-01-05 A 19 True 19 # Reset rolling max for 'A'
1990-01-05 B 65 False 65
1990-01-06 A 17 False 19
1990-01-06 B 20 True 20 # Reset rolling max for 'B'
我该怎么做?
我能够解决这个问题。
df['rolling_max'] = df.groupby(['Symbol',df.groupby('Symbol')['condition'].cumsum()])['number'].cummax()