我有一个Pandas DataFrame和一个DateIndex行。我想要定义一些逻辑来创建一个新列,该列将展望符合某些条件的下一行,然后计算该未来行上的列与当前行之间的差的值。
例如。使用以下DataFrame:
df = pd.DataFrame({'measurement': [101, 322, 313, 454, 511, 234, 122, 134, 222, 321, 221, 432],
'action': [0, 0, 1, 0, 0, -1, 0, 1, 0, 0, 0, -1]})我想在每一列中添加一行,例如,distance_to_action,它由当前measurement值与未来measurement值之间的差异组成,其中action不等于0。
这个是可能的吗?
谢谢!
发布于 2018-10-29 17:17:30
使用pd.merge_asof将最近的未来度量带到新列,然后执行减法。
import pandas as pd
df = pd.merge_asof(df,
df.loc[df.action != 0, ['measurement']],
left_index=True,
right_index=True,
direction='forward',
allow_exact_matches=False, # True if you want same row matches
suffixes=['', '_future'])
df['distance_to_action'] = df.measurement - df.measurement_future输出:
measurement action measurement_future distance_to_action
0 101 0 313.0 -212.0
1 322 0 313.0 9.0
2 313 1 234.0 79.0
3 454 0 234.0 220.0
4 511 0 234.0 277.0
5 234 -1 134.0 100.0
6 122 0 134.0 -12.0
7 134 1 432.0 -298.0
8 222 0 432.0 -210.0
9 321 0 432.0 -111.0
10 221 0 432.0 -211.0
11 432 -1 NaN NaNhttps://stackoverflow.com/questions/53050245
复制相似问题