2017-08-10 205 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