Python报错:The truth value of an array with more than one element is ambiguous
生活随笔
收集整理的這篇文章主要介紹了
Python报错:The truth value of an array with more than one element is ambiguous
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
程序員的一生就是和bug作戰的一生,為了方便后來人以及自己的偶爾復習,特此寫下本篇,記錄自己的錯誤。
目錄
文章目錄
- 前言
- 目錄
- 正文
- 解決方案
正文
在使用python的時候,總是會遇到一些奇特的錯誤,在調用numpy包后,會經常遇到這個錯誤:
DeprecationWarning: The truth value of an empty array is ambiguous. Returning False, but in future this will result in an error. Use `array.size > 0` to check that an array is not empty.今天我們就來解決這個問題:
解決方案
Numpy對邏輯表達式判別不清楚,它可以返回False如果等號兩邊兩個式子是數值相等,也可以返回True因為等號兩邊兩個式子是邏輯相等。它覺得這是模棱兩可的,因此放棄做判斷,統一用a.any()進行或比較,或a.all()進行與比較。可以從下面例子體會一下。
import numpy as numpy a=np.zeros(3) a[0]=0; a[1]=2; a[2]=1 print (a-[0,2,1]).any() #[0,0,0] False print (a-[0,2,1]).all() #[0,0,0] False print (a-[1,3,2]).any() #[-1,-1,-1] True print (a-[1,3,2]).all() #[-1,-1,-1] True print (a-[0,3,2]).any() #[0,-1,-1] True print (a-[0,3,2]).all() #[0,-1,-1] Falsenumpy-array數組進行(a-b)比較時,True表示不同,False表示相同
部分元素相等,numpy.all() 返False(一幫情況下不希望出現),numpy.any() 返回True; 所有元素都相等,二者均返回False 因此最好使用numpy.any() 比較
總結
以上是生活随笔為你收集整理的Python报错:The truth value of an array with more than one element is ambiguous的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springboot 事务_Spring
- 下一篇: 吴恩达 coursera ML 第一课总