获取Pytables一维数组中的值索引

时间:2018-10-22 10:59:17

标签: python arrays python-3.x dictionary pytables

我现在正在为大学编写代码,该代码可处理大量数据,并使用具有各种矩阵/矩阵的Pytables以避免内存溢出,并且到目前为止,它一直运行良好。

现在,我需要为多个不同的String分配一个整数标识符(从0到任何数字),存储该赋值,并能够将对应的整数分配给某个String,反之亦然。当然,普通类型不能削减它,字符串太多了,所以我需要使用与Pytables等文件兼容的东西。

我想到了只使用一维Pytables EArray(因为我不知道会有多少个Strings),将Strings存储在其中,并使每个元素的索引成为String分配的整数标识符。

这是我想到的使用示例:

import tables as tb, numpy as np

>>>file = tb.open_file("sample_file.hdf5", mode='w')
>>>sample_array = file.create_earray(file.root, 'data', tb.StringAtom(itemsize=50),
 shape=(0,), expectedrows=10000)
>>>sample_array.append(np.array(["String_value"]))

那样,我可以获得给定整数的String值,就像在任何普通数组中一样

>>>sample_array[0]
b'String_value'

但是我一生无法找到相反的方法,要找到给定String的索引,我只是想出了更荒谬的方法...

>>> sample_array[np.where("String_value") in sample_array]
b'String_value'
>>> sample_array[np.where("String_value")]
array([b'String_value'], dtype='|S50')
>>> np.where("String_value") in sample_array
False

提前谢谢!

编辑:

忘了更新,我在做其他事情时发现了... Facepalmed很难,非常努力,这确实很愚蠢,但是我几个小时都无法弄清出什么问题了。

np.where(sample_array[:] == b'String_value')
>>>(array([0]),)

1 个答案:

答案 0 :(得分:0)

OP在上面回答了他的问题。但是,它埋在 EDIT:下,因此在搜索结果中(或对普通读者而言)并不明显。另外,还有另一种解决问题的方法(使用代替 Earray )。这提供了两种方法的比较。

带有Earray的OP解决方案(带有点缀):

import tables as tb, numpy as np
h5f = tb.open_file("sample_file.hdf5", mode='w')
sample_array = h5f.create_earray(h5f.root, 'data', tb.StringAtom(itemsize=50),
               shape=(0,), expectedrows=10000)
sample_array.append(np.array(['str_val0']))
sample_array.append(np.array(['str_val10']))
sample_array.append(np.array(['str_val20']))
sample_array.append(np.array(['str_val30']))
sample_array.append(np.array(['str_val40']))
print (sample_array[0])
print (sample_array[-1])
print (np.where(sample_array[:] == b'str_val0'))
print (np.where(sample_array[:] == b'str_val40'))
print ('\n')

h5f.close()

输出看起来像这样:

b'str_val0'
b'str_val40'
(array([0], dtype=int64),)
(array([4], dtype=int64),)

我使用表格的方法
我喜欢Pytables中的Tables。它们很方便,因为它们具有多种内置的搜索和迭代方法(在本例中使用.get_where_list();还有许多其他方法)。此示例显示了从np.recarray创建表(使用dtype定义字段/列,并使用数据填充表)。稍后使用.append()方法添加其他数据行。

import tables as tb, numpy as np
h5f = tb.open_file("sample_file.hdf5", mode='w')

simple_recarray = np.recarray((4,),dtype=[('tstr','S50')])
simple_recarray['tstr'][0] = 'str_val1'
simple_recarray['tstr'][1] = 'str_val2'
simple_recarray['tstr'][2] = 'str_val10'
simple_recarray['tstr'][3] = 'str_val20'

simple_table = h5f.create_table(h5f.root, 'table_data', simple_recarray, 'Simple dataset')

print (simple_table.get_where_list("tstr == b'str_val1'"))
print (simple_table.get_where_list("tstr == b'str_val20'"))

simple_table.append([('str_val30',), ('str_val31',)])

print (simple_table.get_where_list("tstr == b'str_val31'"))

h5f.close()

输出看起来像这样(略有不同的b / c字符串未存储在数组中):

[0]
[3]
[5]