Skip to main content
 首页 » 编程设计

python之如何按列存储在结构化的numpy数组中

2024年12月31日11softidea

我有一个看起来像这样的元组列表:

>>> y 
[(0,1,2,3,4,...,10000), ('a', 'b', 'c', 'd', ...), (3.2, 4.1, 9.2, 12., ...), ] 

等y 有 7 个元组,每个元组有 10,000 个值。给定元组的所有 10,000 个值都是相同的数据类型,我也有这些数据类型的列表:

>>>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,第二个值必须是字符串,依此类推,对于具有 10,000 个值的元组,我只有 7 个 dtype。

我如何与代码沟通,我的意思是第一个元组的 ALL 值是 int64,而第二个元组的 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 数组。

请您参考如下方法:

使用 zip* 习惯用法来“转置”您的元组列表:

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、结构化数组 函数。


如评论:

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')])