python - 将 2-D numpy 数组附加到 3-D numpy 数组

标签 python arrays numpy

我有一个循环,每次都会创建一个新的 (2, 3) 数组。我想将这些数组附加在一起以创建一个新的 3 维数组,我认为一个示例可以解释我最想做的事情。假设我有一个数组 arr1 = array([[1, 2, 3], [4, 5, 6]]) 和一个数组 arr2 = array([[11, 22, 33]、[44、55、66]])。我想通过“添加数组”来获得一个新数组,例如 arr3 = np.array([[[1, 11], [2, 22], [3, 33]], [[4, 44]、[5,55]、[6,66]]])。实际上,这看起来像:

import numpy as np

n_samples = 10
total_arr = np.empty([2, 3, n_samples])

for i in range(n_samples):
   arr = np.random.rand(2,3)
   total_arr.append(arr) #This is the step I don't know what do do with

print(total_arr.shape)
>>> (2, 3, 10) #Where 10 is whatever n_samples is

我当前的方法是将 total_arr 转换为 total_lst = Total_arr.tolist() 的列表,并附加每个 arr[i,j] 使用 for 循环添加到 total_lst 中的列表。所以类似 total_list[i][j].append(arr[i,j]) 但这花费了太长的时间,是否有一个 numpy 解决方案?

谢谢

最佳答案

In [179]: arr1 = np.array([[1, 2, 3], [4, 5, 6]]); arr2 = np.array([[11, 22, 33], [44, 55, 66]])                
In [180]: arr1                                                                                                  
Out[180]: 
array([[1, 2, 3],
       [4, 5, 6]])
In [181]: arr2                                                                                                  
Out[181]: 
array([[11, 22, 33],
       [44, 55, 66]])

np.stack 可以沿着新轴连接数组列表。默认情况下的行为类似于 np.array([arr1, arr2]),但看起来您想要一个新的最后一个轴:

In [182]: np.stack([arr1, arr2], axis=2)                                                                        
Out[182]: 
array([[[ 1, 11],
        [ 2, 22],
        [ 3, 33]],

       [[ 4, 44],
        [ 5, 55],
        [ 6, 66]]])

一般来说,将数组收集到一个列表中并在最后执行一次“连接”是最好的。尝试数组连接迭代会更慢,而且更难正确执行。

或者,您可以创建一个具有正确目标大小的数组,并分配元素/ block 。

===

新的第一个轴示例:

In [183]: np.stack([arr1, arr2])                                                                                
Out[183]: 
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[11, 22, 33],
        [44, 55, 66]]])
In [184]: np.stack([arr1, arr2]).transpose(1,2,0)                                                               
Out[184]: 
array([[[ 1, 11],
        [ 2, 22],
        [ 3, 33]],

       [[ 4, 44],
        [ 5, 55],
        [ 6, 66]]])

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

相关文章:

Python:将浮点范围[0.0,1.0]映射到颜色范围[红色,绿色]?

python - 在 TfidfVectorizer 中删除法语和英语中的停用词

python - Pandas groupby 累积/滚动总和、平均值和标准差

python - numpy:arange 包括端点

python - `numpy.dot` 中的数组顺序

python - 包装一个 Python 对象

PHP 脚本无法从 Python 脚本获取输出

c 指针和数组

javascript - 排列的递归列表

java - 二元运算符的操作数类型错误 "*"