简体   繁体   English

如何在3D numpy数组中堆叠多个2D numpy数组

[英]How to stack multiple 2D numpy arrays in a 3D numpy array

I am extracting features from Audio clips. 我正在从音频剪辑中提取功能。 In doing so for 1 clip a matrix of 20x2 dimension is obtained. 这样做,对于1个剪辑,将获得20x2尺寸的矩阵。 I have around 1000 of such clips. 我有大约1000个这样的剪辑。 I want to store all the data in 1 numpy array of dimension 20x2x1000 . 我想将所有数据存储在尺寸为20x2x1000 1 numpy数组中。 Please suggest a method for the same. 请提出同样的方法。

The function you're looking for is np.stack . 您要查找的功能是np.stack It's used to stack multiple NumPy arrays along a new axis. 它用于沿新轴堆叠多个NumPy数组。

import numpy as np

# Generate 1000 features
original_features = [np.random.rand(20, 2) for i in range(1000)]

# Stack them into one array
stacked_features = np.stack(original_features, axis=2)
assert stacked_features.shape == (20, 2, 1000)

There is a convenient function for this and that is numpy.dstack . 有一个方便的函数,它是numpy.dstack Below is a snippet of code for depth stacking of arrays: 以下是用于数组深度堆栈的代码片段:

# whatever the number of arrays that you have
In [4]: tuple_of_arrs = tuple(np.random.randn(20, 2) for _ in range(10))

# stack each of the arrays along third axis
In [7]: depth_stacked = np.dstack(tuple_of_arrs)

In [8]: depth_stacked.shape
Out[8]: (20, 2, 10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM