How to look back at previous rows from within Pandas dataframe function call?

断了今生、忘了曾经 提交于 2019-12-04 18:58:37

This problem has its roots in NumPy.

def entered_long(df):
  return buy_pattern(df) & (df.High > df.High.shift(1))

entered_long is returning an array-like object. NumPy refuses to guess if an array is True or False:

In [48]: x = np.array([ True,  True,  True], dtype=bool)

In [49]: bool(x)

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

To fix this, use any or all to specify what you mean for an array to be True:

def calc_position(df):
  # sum of current positions + any new positions

  if entered_long(df).any():  # or .all()

The any() method will return True if any of the items in entered_long(df) are True. The all() method will return True if all the items in entered_long(df) are True.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!