将2D数组转换为3D numpy数组 [英] Convert 2D array to 3D numpy array
问题描述
我创建了一个numpy数组,该数组的每个元素都包含一个形状相同的数组(9,5).我想要的是3D阵列.
I have a created a numpy array, each element of the array contains an array of the same shape (9,5). What I want is a 3D array.
我尝试使用np.stack.
I've tried using np.stack.
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)
data1D:
array([list([ pdbID AtomNo Type Eta Theta
0 1a9l.pdb 2.0 G 169.225 212.838
1 1a9l.pdb 3.0 G 168.439 206.785
2 1a9l.pdb 4.0 U 170.892 205.845
3 1a9l.pdb 5.0 G 164.726 225.982
4 1a9l.pdb 6.0 A 308.788 144.370
5 1a9l.pdb 7.0 C 185.211 209.363
6 1a9l.pdb 8.0 U 167.612 216.614
7 1a9l.pdb 9.0 C 168.741 219.239
8 1a9l.pdb 10.0 C 163.639 207.044, pdbID AtomNo Type Eta Theta
1 1a9l.pdb 3.0 G 168.439 206.785
2 1a9l.pdb 4.0 U 170.892 205.845
3 1a9l.pdb 5.0 G 164.726 225.982
4 1a9l.pdb 6.0 A 308.788 144.370
5 1a9l.pdb 7.0 C 185.211 209.363
6 1a9l.pdb 8.0 U 167.612 216.614
7 1a9l.pdb 9.0 C 168.741 219.239
8 1a9l.pdb 10.0 C 163.639 207.044
我收到此错误:无法将尺寸为9的序列复制到尺寸为5的数组轴上
I get this error: cannot copy sequence with size 9 to array axis with dimension 5
我想创建一个3D矩阵,其中每个子数组都在新的3D维度中.我猜想新形状是(9,5,350)
I want to create a 3D Matrix, where every subarray is in the new 3D dimension. I gues the new shape would be (9,5,350)
推荐答案
您需要使用
data.reshape((data.shape[0], data.shape[1], 1))
示例
来自numpy导入数组的
from numpy import array
data = [[11, 22],
[33, 44],
[55, 66]]
data = array(data)
print(data.shape)
data = data.reshape((data.shape[0], data.shape[1], 1))
print(data.shape)
运行示例首先打印2D数组中每个尺寸的大小,重新排列数组的形状,然后总结新3D数组的形状.
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.
结果
(3,2)
(3,2,1)
来源: https://machinelearningmastery.com/index-slice-reshape-numpy-arrays-machine-learning-python/
这篇关于将2D数组转换为3D numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!