ValueError: The truth value of a Series is ambiguous. Use a.empty……解决方案

df = pd.DataFrame.from_records(all_data[600000]) 

	short_ma = df["close"].rolling(short_period).mean()
	long_ma = df["close"].rolling(long_period).mean()
	
	prev_short_ma = short_ma.shift(1)   # 前一个值
	prev_long_ma = long_ma.shift(1)
	
	signals = prev_short_ma < prev_long_ma and short_ma > long_ma

这段代码引发了一系列的问题。

运行时,报错:

Traceback (most recent call last):
  File "1.py", line 21, in 
    if prev_short_ma > prev_long_ma and short_ma > long_ma:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

经过一番查证,找到了一个看不懂的解决方案:

signals = prev_short_ma < prev_long_ma and short_ma > long_ma

更改为:

signals = prev_short_ma < prev_long_ma & short_ma > long_ma

& 和 and 在python中不是不通用的吗?

继续运行,报错变成了:

  File "1.py", line 25, in 
    signals = prev_short_ma < prev_long_ma & short_ma > long_ma
TypeError: unsupported operand type(s) for &: 'float' and 'bool'

这句是看明白了,也知道为什么会这样,因为结果里确实有浮点数和布尔值两种,可是该怎么改呢?

解决方案:

signals = (prev_short_ma < prev_long_ma) & (short_ma > long_ma)

让我大跌眼镜的解决方案,不过确实正常运行了,python代码真神奇,用一个()就将浮点数变成了bool类型

你可能感兴趣的:(ValueError: The truth value of a Series is ambiguous. Use a.empty……解决方案)