2015-01-10 34 views
4

我有兩個numpy數組,包含帶有重載比較運算符的對象,該運算符返回另一個對象,而不是True或False。我如何創建一個包含單個比較結果的數組。我想結果是物體的像一個數組中緊隨其後numpy元素與重載運算符的比較

lhs = ... # np.array of objects with __le__ overloaded 
rhs = ... # another np.array 
result = np.array([l <= r for l, r in izip(lhs, rhs)]) 

lhs <= rhs給我的bool數組。 有沒有辦法去result作爲__le__方法調用的結果數組而不寫一個python循環?

+3

np.less_equal(和其他比較函數)的[documentation](http://docs.scipy.org/doc/numpy/reference/generated/numpy.less_equal.html#numpy.less_equal)表示它返回比較的「真值」,所以如果不手動迭代數組,就可能無法做到這一點。 – BrenBarn

回答

3

Numpy's Github page on ndarray指出比較運算符相當於Numpy中的ufunc表單。因此lhs <= rhs相當於np.less_equal(lhs, rhs)

np.info(np.less_equal)

Returns 
------- out : bool or ndarray of bool 
    Array of bools, or a single bool if `x1` and `x2` are scalars. 

輸出要解決這個問題,你可以使用:

import operator 
result = np.vectorize(operator.le)(lhs, rhs) 

np.vectorize將允許您使用NumPy的廣播在比較過。它將使用您的對象比較,並將以與列表理解相同的形式返回這些比較結果的數組。

+0

我們不允許看到的'__le__'函數在普通的舊Python列表理解中運行,而不是一個numpy上下文。因此,不調用np.less_equal。 – msw

+1

@msw'lhs <= rhs'是OP想要使用的,它調用'np.less_than',我說明它爲什麼會返回bool而不是他預期的比較結果。 – ryanpattison