【问题标题】:Add column based on previous values with pandas (python)使用熊猫(python)根据以前的值添加列
【发布时间】:2020-06-03 23:18:45
【问题描述】:

我想在我的 (ohlcv) 数据框中添加一个名为 BullTrend 的新列,该数据框基于 2 列的先前值:

  • 如果当前和前 11 行收盘价高于 EMA -> 牛市趋势值更改为 True
  • 如果当前和前 11 行收盘价低于 EMA -> 牛市趋势值变为False
  • 第一个值 -> BullTrend 的值变为 NaN
  • 不包括最后一行

数据集:

             timestamp    open    high     low   close    volume          ema
    0    1591162860000  9490.0  9489.5  9489.5  9489.5       1.0  9489.500000
    1    1591162920000  9489.5  9490.0  9490.0  9490.0     406.0  9489.751250
    2    1591162980000  9490.0  9490.0  9490.0  9490.0     488.0  9489.834997
    3    1591163040000  9490.0  9497.0  9489.5  9489.5   12798.0  9489.749988
    4    1591163100000  9489.5  9497.0  9489.0  9497.0    1866.0  9491.229134
    ..             ...     ...     ...     ...     ...       ...          ...
    495  1591192560000  9524.5  9524.5  9524.0  9524.5    1727.0  9564.513010
    496  1591192620000  9524.5  9524.5  9523.0  9523.0  179978.0  9564.097058
    497  1591192680000  9523.0  9524.0  9523.0  9524.0     582.0  9563.695321
    498  1591192740000  9524.0  9523.0  9523.0  9523.0       2.0  9563.287617
    499  1591192800000  9523.0  9524.0  9523.0  9524.0    1324.0  9562.894044

列示例:

     bullTrend 
0    NaN
1    NaN
2    NaN
3    NaN
4    True
..             ...
495  True
496  True
497  False
498  False
499  False

【问题讨论】:

标签: python python-3.x pandas


【解决方案1】:

这应该可行:

def isBull(row):
    idx = row.name
    if idx in idxs:
        return row['eta'] < min([df.at[idx-i, 'close'] for i in range(12)])
    else:
        return np.nan

idxs = df.index[12:-1]
df['bullTrend'] = df.apply(isBull, axis=1)

【讨论】:

    猜你喜欢
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 2014-08-31
    • 2019-06-05
    • 2023-02-09
    相关资源
    最近更新 更多