numpy重塑如何工作? [英] How does numpy reshape works?

查看:66
本文介绍了numpy重塑如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy数组中的数据:

I have data in a numpy array:

a = np.arange(100)
a = a.reshape((20,5))

当我键入

a[:10]

它返回

array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24],
       [25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34],
       [35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44],
       [45, 46, 47, 48, 49]])

现在我决定将阵列重塑为3d阵列.

Now i decided to reshape the array into 3d array.

b = a.reshape((5,4,5))

array([[[ 0,  1,  2,  3,  4],
    [ 5,  6,  7,  8,  9],
    [10, 11, 12, 13, 14],
    [15, 16, 17, 18, 19]],

   [[20, 21, 22, 23, 24],
    [25, 26, 27, 28, 29],
    [30, 31, 32, 33, 34],
    [35, 36, 37, 38, 39]],

   [[40, 41, 42, 43, 44],
    [45, 46, 47, 48, 49],
    [50, 51, 52, 53, 54],
    [55, 56, 57, 58, 59]],

   [[60, 61, 62, 63, 64],
    [65, 66, 67, 68, 69],
    [70, 71, 72, 73, 74],
    [75, 76, 77, 78, 79]],

   [[80, 81, 82, 83, 84],
    [85, 86, 87, 88, 89],
    [90, 91, 92, 93, 94],
    [95, 96, 97, 98, 99]]])

如何对b进行切片,以获得类似于a [:10]的值?我尝试过

How do I slice b to that I obtain the values like a[:10]? I tried

b[:10,0,:5]
array([[ 0,  1,  2,  3,  4],
       [10, 11, 12, 13, 14],
       [20, 21, 22, 23, 24],
       [30, 31, 32, 33, 34],
       [40, 41, 42, 43, 44],
       [50, 51, 52, 53, 54],
       [60, 61, 62, 63, 64],
       [70, 71, 72, 73, 74],
       [80, 81, 82, 83, 84],
       [90, 91, 92, 93, 94]])

但它不正确.预先谢谢你!

But its not correct. Thank you in advance!

推荐答案

使用 b = a.reshape((5,4,5))时,您只是在同一视图上创建了一个不同的视图数组 a 使用的数据.(即,对 a 元素的更改将显示在 b 中). reshape()在这种情况下不会复制数据,因此这是一个非常快速的操作.切片 b 和切片 a 会访问相同的内存,因此对于 b 数组不需要使用不同的语法(只需使用 a [:10] ).如果您已经创建了数据副本(也许使用 np.resize())并丢弃了 a ,则只需重塑 b : b.reshape((20,5))[:10] .

When you use b = a.reshape((5,4,5)) you just create a different view on the same data used by the array a. (ie changes to the elements of a will appear in b). reshape() does not copy data in this case, so it is a very fast operation. Slicing b and slicing a accesses the same memory, so there shouldn't be any need for a different syntax for the b array (just use a[:10]). If you have created a copy of the data, perhaps with np.resize(), and discarded a, just reshape b: b.reshape((20,5))[:10].

这篇关于numpy重塑如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆