通常,如果只需要访问的滞后版本,则无需创建额外的列epoch
。df.groupby('id')
然后,您只需['epoch'].shift(1)
在每个分组数据框中引用即可。
但如果你真的坚持这样的话,使用解决方案布尔索引,shift()
并且fillna()
:
# Do the default lagged assignment for all rows where 'epoch' != 1
df['previous_epoch_stage'] = df.groupby('id')['epoch'].shift(1)
# Now fill NA's in-place from the 'stage' column
df['previous_epoch_stage'].fillna(df['stage'], inplace=True)
# and if you want to reverse fillna and the NaNs coercing your ints to floats:
df['previous_epoch_stage'] = df['previous_epoch_stage'].astype(int)
笔记:
previous_epoch_stage
使用stage
epoch-1行中的值填充列”epoch
df['stage'].head()
df.where(cond, other, ...)
](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.where.html)进行向量化if-else,在这种情况下other
,需要是一个函数(“可调用”),但在groupby上不能很好地发挥作用,因此请使用布尔索引。fill_value=NaN
或指定任意值periods
(+ ve或-ve)。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句