我有两个不同的数组,一个是字符串,另一个是整数。我想将它们连接成一个数组,其中每列都有原始数据类型。我目前的解决方案(见下文)将整个数组转换为dtype = string,这看起来效率很低。将不同的数据类型存储在一个NumPy数组中?
combined_array = np.concatenate((A, B), axis = 1)
是否有可能在combined_array
时A.dtype = string
和B.dtype = int
多发dtypes?
我有两个不同的数组,一个是字符串,另一个是整数。我想将它们连接成一个数组,其中每列都有原始数据类型。我目前的解决方案(见下文)将整个数组转换为dtype = string,这看起来效率很低。将不同的数据类型存储在一个NumPy数组中?
combined_array = np.concatenate((A, B), axis = 1)
是否有可能在combined_array
时A.dtype = string
和B.dtype = int
多发dtypes?
一种方法可能是使用record array。 “列”不会像标准numpy的阵列的列,但对于大多数使用情况下,这已经足够:
>>> 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])
请注意,您还可以通过指定的数据类型做一个标准数组类似的东西阵列。这被称为“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')])
的区别在于,记录阵列还允许属性访问各数据字段。标准结构化数组不。
>>> 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'
这个替代工作很好,谢谢。 – veor
一个简单的解决方案:将您的数据为对象 'O' 型
z = np.zeros((2,2), dtype='U2')
o = np.ones((2,1), dtype='O')
np.hstack([o, z])
创建阵列:
array([[1, '', ''],
[1, '', '']], dtype=object)
的问题是有关使用NumPy的阵列。但是,如果有一个NumPy数组不是必需的,那么[Pandas DataFrame](http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe)对于这种情况将会很好。 – crayzeewulf