存储在一个numpy的阵列不同的数据类型? [英] Store different datatypes in one NumPy array?
问题描述
我有两个不同的阵列,用绳子和另一台整数。我想将它们连接起来,到一个数组,其中每列具有原始数据类型。我这样做的(见下文),目前的解决方案对整个数组DTYPE =字符串,它似乎很低效的内存转换。
I have two different arrays, one with strings and another with ints. I want to concatenate them, into one array where each column has the original datatype. My current solution for doing this (see below) converts the entire array into dtype = string, which seems very memory inefficient.
combined_array = np.concatenate((A,B),轴= 1)
是否有可能多发dtypes在 combined_array
在 A.dtype =字符串
和 B.dtype = INT
?
Is it possible to mutiple dtypes in combined_array
when A.dtype = string
and B.dtype = int
?
推荐答案
一个办法可能是使用的记录阵列。 列不会像标准numpy的阵列中的列,但对于大多数使用情况下,这是足够了:
One approach might be to use a record array. The "columns" won't be like the columns of standard numpy arrays, but for most use cases, this is sufficient:
>>> a = numpy.array(['a', 'b', 'c', 'd', 'e'])
>>> b = numpy.arange(5)
>>> records = numpy.rec.fromarrays((a, b), names=('keys', 'data'))
>>> records
rec.array([('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4)],
dtype=[('keys', '|S1'), ('data', '<i8')])
>>> records['keys']
rec.array(['a', 'b', 'c', 'd', 'e'],
dtype='|S1')
>>> records['data']
array([0, 1, 2, 3, 4])
请注意,您也可以通过指定数组的数据类型做一个标准数组类似的东西。这被称为结构阵列的
Note that you can also do something similar with a standard array by specifying the datatype of the array. This is known as a "structured array":
>>> arr = numpy.array([('a', 0), ('b', 1)],
dtype=([('keys', '|S1'), ('data', 'i8')]))
>>> arr
array([('a', 0), ('b', 1)],
dtype=[('keys', '|S1'), ('data', '<i8')])
的区别在于,记录阵列还允许个别数据字段属性的访问。标准的结构化数组没有。
The difference is that record arrays also allow attribute access to individual data fields. Standard structured arrays do not.
>>> records.keys
chararray(['a', 'b', 'c', 'd', 'e'],
dtype='|S1')
>>> arr.keys
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'keys'
这篇关于存储在一个numpy的阵列不同的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!