2016-05-12 64 views
0

我有下面的類:如何使用數組中的np.where()與類的實例?

class IdFuns(object): 
    def __init__(self,i,p,v,u): 
     self.i = i 
     self.p = p 
     self.v = v 
     self.u = u 

當我把一個循環我得到以下數組類的實例裏面:

array([ 
    <__main__.IdFuns object at 0x7fc8362e8250>, 
    <__main__.IdFuns object at 0x7fc8362e8290>, 
    <__main__.IdFuns object at 0x7fc8362e82d0>, 
    <__main__.IdFuns object at 0x7fc8362e8310>, 
    <__main__.IdFuns object at 0x7fc8362e8350>, 
    <__main__.IdFuns object at 0x7fc8362e8390>, 
    <__main__.IdFuns object at 0x7fc8362e83d0>, 
    <__main__.IdFuns object at 0x7fc8362e8410>, 
    <__main__.IdFuns object at 0x7fc8362e8450>, 
    <__main__.IdFuns object at 0x7fc8362e8490>, 
    <__main__.IdFuns object at 0x7fc8362e84d0>, 
    <__main__.IdFuns object at 0x7fc8362e8510>, 
    <__main__.IdFuns object at 0x7fc8362e8550>], dtype=object) 

我想知道我怎麼使用np.where ()來搜索我是否有例如.i = 1的實例。

回答

2

.i單個項目在屬性對象數組中的屬性,而不是數組本身。因此,您使用列表理解需要循環使用Python這些項目,例如:

bool_idx = [item.i == 1 for item in object_array] 

這則作爲第一個參數傳遞給np.where

locs = np.where(bool_idx) 

總的來說,我建議您避免使用np.object陣列。由於它們不支持矢量化操作,因此它們不會比標準Python list提供任何顯着的性能改進。它看起來好像你可能會更好使用structured numpy arraypandas.DataFrame

+0

謝謝!它會幫助我很多。 – dalmeida13

相關問題