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

标签 python list numpy multidimensional-array

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

我试过使用 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 的数组轴

我想创建一个 3D 矩阵,其中每个子数组都在新的 3D 维度中。我猜新的形状是 (9,5,350)

最佳答案

You need to use


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

Example


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)

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/

关于python - 将 2D 数组转换为 3D numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56634634/

相关文章:

python - 在 Django 模板中通过 {% url %} 传递命名模式参数

Python 3.6.1 - Numpy.power 返回正 int 数的立方幂的负值

python - MySQL 连接器 Python 变量未注册

python - python属性的get和set顺序是什么?

python - 如何使用列表推导式使每个元素成为 zip() 的列表?

python - 这段关于加泰罗尼亚数字的 Python 代码有什么问题?

html - 3个ul在一行中,如何证明在div顶部开始?

python - n 个列表中项目的所有可能组合

python - Numpy:用 numpy 数组替换 numpy 数组中的零

python - 如何将数字 numpy 数组更改为 char 数组?