我有一个看起来像这样的元组列表:
>>> y
[(0,1,2,3,4,...,10000), ('a', 'b', 'c', 'd', ...), (3.2, 4.1, 9.2, 12., ...), ]
等。 y
有7个元组,每个元组有10,000个值。给定元组的所有10,000个值都是相同的dtype,我也有这些dtypes的列表:
>>>dt
[('0', dtype('int64')), ('1', dtype('<U')), ('2', dtype('<U')), ('3', dtype('int64')), ('4', dtype('<U')), ('5', dtype('float64')), ('6', dtype('<U'))]
我的目的是做x = np.array(y, dtype=dt)
之类的事情,但当我这样做时,我收到以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not assign tuple of length 10000 to structure with 7 fields.
我知道这是因为dtype说元组中的第一个值必须是int64,第二个值必须是字符串,依此类推,而且我只有7个dtypes用于具有10,000个值的元组。
我如何与代码进行通信,我的意思是第一个元组的 ALL 值是int64s,第二个元组的 ALL 值是字符串等?
我还尝试将y
列为列表而不是元组列表:
>>>y
[[0,1,2,3,4,...,10000], ['a', 'b', 'c', 'd', ...), ...]
等,由于与上述相同的原因我收到错误:
>>> x = np.array(y, dtype=dt)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Supplier#000000001'
感谢任何帮助!
编辑:我的目标是让x成为一个numpy数组。
答案 0 :(得分:1)
使用zip*
成语转换&#39;你的元组列表:
In [150]: alist = [(0,1,2,3,4),tuple('abcde'),(.1,.2,.4,.6,.8)]
In [151]: alist
Out[151]: [(0, 1, 2, 3, 4), ('a', 'b', 'c', 'd', 'e'), (0.1, 0.2, 0.4, 0.6, 0.8)]
In [152]: dt = np.dtype([('0',int),('1','U3'),('2',float)])
In [153]: list(zip(*alist))
Out[153]: [(0, 'a', 0.1), (1, 'b', 0.2), (2, 'c', 0.4), (3, 'd', 0.6), (4, 'e', 0.8)]
In [154]: np.array(_, dt)
Out[154]:
array([(0, 'a', 0.1), (1, 'b', 0.2), (2, 'c', 0.4), (3, 'd', 0.6),
(4, 'e', 0.8)], dtype=[('0', '<i8'), ('1', '<U3'), ('2', '<f8')])
还有一个recarray
创建者,它接受一个数组列表:
In [160]: np.rec.fromarrays(alist,dtype=dt)
Out[160]:
rec.array([(0, 'a', 0.1), (1, 'b', 0.2), (2, 'c', 0.4), (3, 'd', 0.6),
(4, 'e', 0.8)],
dtype=[('0', '<i8'), ('1', '<U3'), ('2', '<f8')])
还有一个numpy.lib.recfunctions
模块(单独导入),具有recarray, structured array
个功能。
评论如下:
In [169]: np.fromiter(zip(*alist),dt)
Out[169]:
array([(0, 'a', 0.1), (1, 'b', 0.2), (2, 'c', 0.4), (3, 'd', 0.6),
(4, 'e', 0.8)], dtype=[('0', '<i8'), ('1', '<U3'), ('2', '<f8')])
答案 1 :(得分:0)
可能不是最优雅的解决方案,但列表理解有效:
x = [np.array(tup, dtype=typ[1]) for tup, typ in zip(y, dt)]