将2D数组转换为3D numpy数组

2024-06-17 09:22:08 发布

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

我创建了一个numpy数组,数组的每个元素都包含一个形状相同的数组(9,5)。我想要的是一个三维阵列。在

我试过用np.堆栈. 在

data = list(map(lambda x: getKmers(x, 9), data)) # getKmers creates a       
                                                 # list of list from a pandas dataframe
data1D = np.array(data)                          # shape (350,)
data2D = np.stack(data1D)

^{pr2}$

我得到这个错误: 无法将大小为9的序列复制到维度为5的数组轴

我想创建一个3D矩阵,其中每个子阵列都在新的3D维度中。我想新的形状应该是(95350)


Tags: oflambdafromnumpy元素mapdata堆栈
3条回答

You need to use

 data.reshape((data.shape[0], data.shape[1], 1))

Example

^{pr2}$

Running the example first prints the size of each dimension in the 2D array, reshapes the array, then summarizes the shape of the new 3D array.

Result

(3,2)
(3,2,1)

Source :https://machinelearningmastery.com/index-slice-reshape-numpy-arrays-machine-learning-python/

如果你想创建一个3D矩阵,其中每个子数组都在新的3D维中,那么最终的形状不是(350,9,5)?在这种情况下,您可以简单地使用:

new_array = np.asarray(data).reshape(350,9,5)

从您的问题看来,getKmers(x,9)生成一个由9个长度350个列表组成的列表,data输入有5个元素。你需要一个(9350)数组。这可以通过以下方式实现:

arr = np.swapaxes([getKermers(x, 9) for x in data], 0, 1)

注意,swapaxes与整形不同。如果你只是做np.array([getKermers(x, 9) for x in data]).reshape(9, 5, 350),你会得到想要的输出形状,但是你的数据顺序会错误。在

相关问题 更多 >