2017-08-10 212 views
0

我有一個數組的值爲0-5,我想用numpy.where()來獲取項目等於1的指數,但是它返回一個空數組。numpy.where()返回空列表,當項目滿足條件

代碼:

hf = h5py.File(PATH+'/data.h5', 'r') 
data = hf['data']     #dtype int32 [0,1,2,3,4,2,3,1,1,1,4,5,6] 
print(data[1] == 1)     #prints True 
indices = np.where(data == 1)[0]  #ERROR here - returns empty array 

回答

1

您必須下載到像這樣進行測試的數據集。

使用測試文件,我已經掛在:

In [318]: f = h5py.File('data.h5') 
In [319]: list(f.keys()) 
Out[319]: ['dset', 'dset1', 'vset'] 
In [320]: f['dset'] 
Out[320]: <HDF5 dataset "dset": shape (3, 5), type "<f8"> 

我可以索引和測試單個項目或數據集

In [321]: f['dset'][1] 
Out[321]: array([ 1., 1., 1., 1., 1.]) 
In [322]: f['dset'].shape 
Out[322]: (3, 5) 
In [323]: f['dset'][...] 
Out[323]: 
array([[ 1., 1., 1., 1., 1.], 
     [ 1., 1., 1., 1., 1.], 
     [ 1., 1., 1., 1., 1.]]) 

的片,但在數據集上的布爾測試不工作:

In [324]: f['dset']>0 
... 
TypeError: unorderable types: Dataset() > int() 

==1工作,但比較數據集對象與1,並不可避免地返回s False。這就是爲什麼where爲您提供了一個空的結果:

In [325]: f['dset']==1 
Out[325]: False 

要進行其他的元素測試的元素我有「索引」的數據集:

In [326]: f['dset'][...]>0 
Out[326]: 
array([[ True, True, True, True, True], 
     [ True, True, True, True, True], 
     [ True, True, True, True, True]], dtype=bool) 
+0

我解決它,改成:'數據= HF ['data'] [::]'。謝謝:)我必須等幾分鐘才能接受你的答案。 – matchifang

+0

我相信你也可以在HDF5數據集對象上調用'np.array'來創建一個numpy數組。 – Praveen

+0

我推薦'f ['dset'] .value'在'np.array(f ['dset'])''上。無論如何,我們需要知道'dataset'和內存中的數組是有區別的。 – hpaulj