将列表数组转换为元组数组/trip

2024-05-16 03:21:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有3列的2D Numpy数组。它看起来像这样array([[0, 20, 1], [1,2,1], ........, [20,1,1]])。它基本上是列表的数组。如何将此矩阵转换为array([(0,20,1), (1,2,1), ........., (20,1,1)])?我希望输出是一个三元组的数组。我一直在尝试使用Convert numpy array to tuple中描述的元组和映射函数

R = mydata #my data is sparse matrix of 1's and 0's
#First row
#R[0] = array([0,0,1,1]) #Just a sample
(rows, cols) = np.where(R)
vals = R[rows, cols]
QQ = zip(rows, cols, vals)
QT = tuple(map(tuple, np.array(QQ))) #type of QT is tuple

QTA = np.array(QT) #type is array
#QTA gives an array of lists
#QTA[0] = array([0, 2, 1])
#QTA[1] = array([0, 3, 1])

但是期望的输出是QTA应该是元组数组,即QTA=array([(0,2,1),(0,3,1)])。在


Tags: ofnumpyistypenp数组qtarray
2条回答

不是很好的解决方案,但这会奏效:

# take from your sample
>>>a = np.array([[0, 20, 1], [1,2,1], [20,1,1]]) 

# construct an empty array with matching length
>>>b = np.empty((3,), dtype=tuple)

# manually put values into tuple and store in b
>>>for i,n in enumerate(a):
>>>    b[i] = (n[0],n[1],n[2])

>>>b
array([(0, 20, 1), (1, 2, 1), (20, 1, 1)], dtype=object)

>>>type(b)
numpy.ndarray

你的2d数组不是一个列表列表,但是它可以很容易地转换成列表

a.tolist()

如Jimbo所示,您可以将其转换为带有comprehension(amap也可以)的元组列表。但是当你试图把它包装成一个数组,你又得到了2d数组。这是因为np.array试图创建尽可能大的维度数组。如果子列表(或元组)的长度相同,这就是一个二维数组。在

要保留元组,必须切换到结构化数组。例如:

^{pr2}$

在这里,我创建了一个空的结构化数组,dtype object,这是最普通的类型。然后我使用元组列表分配值,这是该任务的正确数据结构。在

另一种数据类型是

a1=np.empty((2,), dtype='int,int,int')
....
array([(0, 20, 1), (1, 2, 1)], 
      dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4')])

或者一步到位:np.array([tuple(i) for i in a], dtype='int,int,int')

a1=np.empty((2,), dtype='(3,)int')生成二维数组。dt=np.dtype([('f0', '<i4', 3)])产生

array([([0, 20, 1],), ([1, 2, 1],)], 
      dtype=[('f0', '<i4', (3,))])

它在元组中嵌套1d数组。所以看起来object或3个字段是我们能得到的最接近元组数组的。在

相关问题 更多 >