【问题标题】:Compute pandas DataFrame column for value between current row and a future row matching criteria为当前行和未来行匹配条件之间的值计算 pandas DataFrame 列
【发布时间】:2018-10-30 01:17:30
【问题描述】:

我有一个带有 DateIndex 行的 Pandas 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 .

这可能吗?

谢谢!

【问题讨论】:

  • 你能举例说明你的预期输出吗?

标签: pandas


【解决方案1】:

使用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                 NaN

【讨论】:

  • 太棒了!谢谢你:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-01
  • 2019-12-23
  • 1970-01-01
  • 1970-01-01
  • 2016-08-23
相关资源
最近更新 更多