python ValueError: 明明可以判断True or False还报错

python ValueError: 明明可以判断True or False还报错

明明可以判断True or False
为什么还是会报错:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

jump_pd=pd.DataFrame()
for kl_index in np.arange(1,stock.shape[0]):

today=(stock[kl_index:kl_index+1])

yesday=(stock[kl_index-1:kl_index])

stock.iloc[kl_index,10]= yesday.Close

print (today['pct_change'] > 0 )

print (today['pct_change'] )

print('**********************')

if today['pct_change'] > 0 :

#today['jump_power']=(today.Low -today['preClose'])

print(today)

     Date

2017-01-04 False

Name: pct_change, dtype: bool# print (today['pct_change'] > 0 ) output

Date

2017-01-04 0.0

Name: pct_change, dtype: float64# print (today['pct_change'] ) output

***********************# print('**********************') output

---------------------------------------------------------------------------

ValueError Traceback (most recent call last)

<ipython-input-430-807a41469f87> in <module>

7 print (today['pct_change'] )

8 print('**********************')

----> 9 if today['pct_change'] > 0 :

10 #today['jump_power']=(today.Low -today['preClose'])

11 print(today)

D:\PF\tools\Anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)

1440 @final

1441 def __nonzero__(self):

-> 1442 raise ValueError(

1443 f"The truth value of a {type(self).__name__} is ambiguous. "

1444 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."

> ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

if today['pct_change'] > 0 :这一句怎么就报错了
感谢。


回答:

你的today是一个1行的dataframe,而不是series。
today['pct_change']>0是一个值为True/False的series,虽然它只有1个值。bool(series)是没有严格定义的,这就是报错的原因。
就像列表,l[x]返回的是元素y,l[x:x+1]返回的是列表[y]。

以上是 python ValueError: 明明可以判断True or False还报错 的全部内容, 来源链接: utcz.com/p/937972.html

回到顶部