python - 从数组的数组中提取数组

标签 python numpy

我有这个数组:

arr = np.array([[[ -1.,  -1.,  -1.,  0.,   0.,   0.],
                [ 0.1,  0.1,  0.1,  2.,   3.,   4.]], # <-- this one

               [[ -1.,  -1.,  -1.,  0.,   0.,  -1.],
                [ 0.1,  0.1,  0.1, 16.,  17.,  0.1]], # <-- and this one

               [[ -1.,  -1.,  -1.,  0.,   0.,   0.],
                [ 0.1,  0.1,  0.1,  4.,   5.,   6.]], # <-- and this one

               [[  0.,   0.,   0., -1.,   0.,   0.],
                [  1.,   2.,   3., 0.1,   1.,   2.]], # <-- and this one

               [[ -1.,  -1.,   0.,  0.,   0.,   0.],
                [ 0.1,  0.1,   1.,  9.,  10.,  11.]]]) # <-- and the last one

我想提取每个数组中的第2个数组,结果应该如下:

res = [[ 0.1,  0.1,  0.1,  2.,   3.,   4.],
       [ 0.1,  0.1,  0.1, 16.,  17.,  0.1],
       [ 0.1,  0.1,  0.1,  4.,   5.,   6.],
       [  1.,   2.,   3., 0.1,   1.,   2.],
       [ 0.1,  0.1,   1.,  9.,  10.,  11.]]

我想在一行代码中获取res,我试过了但是没有成功

arr[:][1] # select the element 1 in each array
# I got
array([[ -1. ,  -1. ,  -1. ,   0. ,   0. ,  -1. ],
       [  0.1,   0.1,   0.1,  16. ,  17. ,   0.1]])

谁能解释一下为什么?

我找到的唯一解决方案是明确指示每个索引 (arr[0][1]...),我不喜欢这样。

最佳答案

这是一个 3D 数组,您正试图选择第二个轴的第二个元素并提取其余轴上的所有元素。所以,它很简单——

arr[:,1,:]

我们可以跳过列出尾随轴的 :,因此它进一步简化为 -

arr[:,1]

sample 运行-

In [360]: arr
Out[360]: 
array([[[ -1. ,  -1. ,  -1. ,   0. ,   0. ,   0. ],
        [  0.1,   0.1,   0.1,   2. ,   3. ,   4. ]],

       [[ -1. ,  -1. ,  -1. ,   0. ,   0. ,  -1. ],
        [  0.1,   0.1,   0.1,  16. ,  17. ,   0.1]],

       [[ -1. ,  -1. ,  -1. ,   0. ,   0. ,   0. ],
        [  0.1,   0.1,   0.1,   4. ,   5. ,   6. ]],

       [[  0. ,   0. ,   0. ,  -1. ,   0. ,   0. ],
        [  1. ,   2. ,   3. ,   0.1,   1. ,   2. ]],

       [[ -1. ,  -1. ,   0. ,   0. ,   0. ,   0. ],
        [  0.1,   0.1,   1. ,   9. ,  10. ,  11. ]]])

In [361]: arr[:,1]
Out[361]: 
array([[  0.1,   0.1,   0.1,   2. ,   3. ,   4. ],
       [  0.1,   0.1,   0.1,  16. ,  17. ,   0.1],
       [  0.1,   0.1,   0.1,   4. ,   5. ,   6. ],
       [  1. ,   2. ,   3. ,   0.1,   1. ,   2. ],
       [  0.1,   0.1,   1. ,   9. ,  10. ,  11. ]])

关于python - 从数组的数组中提取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43634508/

相关文章:

python - Pandas 删除所有包含任何 nan 的列,除了一个

python - 任何 Python 内置 API 返回列表的最小元素索引

python - 'AxesSubplot' 对象没有属性 'get_axis_bgcolor'

python 日志记录如何将日志文件创建为 html

python - 使用 NumPy 平均来自 Python 中两个配对列表的重复值

python - 如何绘制 scipy 优化结果

python - 如何在使用 pandas.read_csv 读取 csv 文件时将 pandas.dataframe 中的元素转换为 np.float?

python - 具有多个选项的 while 循环中的键盘输入

python - Numpy IndexError 使用 genfromtxt 和第一列字符串读取 csv

python - 查找一个数据集中的数据在另一数据集中的对应关系