简体   繁体   中英

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. I have around 1000 of such clips. I want to store all the data in 1 numpy array of dimension 20x2x1000 . Please suggest a method for the same.

The function you're looking for is np.stack . It's used to stack multiple NumPy arrays along a new axis.

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 . 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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