脾气暴躁的:视图vs通过切片复制 [英] Numpy: views vs copy by slicing

查看:64
本文介绍了脾气暴躁的:视图vs通过切片复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我进行切片时,发生了意外的事情,似乎第一个出现在视图中,而第二个出现在复制中.

When I am doing the slicing, an unexpected thing happened that seems the first to be view but the second is copy.

首先是行的切片,然后是列的切片.看来是风景.

First slice of row, then slice of column. It seems is a view.

>>> a = np.arange(12).reshape(3, 4)   
>>> a[0:3:2, :][:, [0, 2]] = 100
>>> a
array([[100,   1, 100,   3],
       [  4,   5,   6,   7],
       [100,   9, 100,  11]])

第二

但是,如果我先是列的一部分,然后是行的一部分,那似乎是副本:

Second

But if I first slice of column, then slice of row, it seems a copy:

>>> a[:, [0, 2]][0:3:2, :] = 0
>>> a
array([[100,   1, 100,   3],
       [  4,   5,   6,   7],
       [100,   9, 100,  11]])

我很困惑,因为这两种方法最终都会导致看似位置发生变化,但是为什么第二种方法实际上并没有改变数字?

I am confused because the two methods finally will cause seem position to change, but why the second actually doesn't change the number?

推荐答案

所有重要的事情是按行还是按列切片.按行切片可以返回视图,因为它是原始数组的连续段.按列切片必须返回一个副本,因为它不是连续的段.例如:

All that matters is whether you slice by rows or by columns. Slicing by rows can return a view because it is a contiguous segment of the original array. Slicing by column must return a copy because it is not a contiguous segment. For example:

A1 A2 A3
B1 B2 B3
C1 C2 C3

默认情况下,它是通过以下方式存储在内存中的:

By default, it is stored in memory this way:

A1 A2 A3 B1 B2 B3 C1 C2 C3

因此,如果要选择第二行,则为:

So if you want to choose every second row, it is:

[A1 A2 A3] B1 B2 B3 [C1 C2 C3]

可以描述为{start: 0, size: 3, stride: 6}.

但是,如果您想选择第二列:

But if you want to choose every second column:

[A1] A2 [A3 B1] B2 [B3 C1] C2 [C3]

并且无法使用一个开始,一个大小和一个步幅来描述它.因此,没有办法构造这样的视图.

And there is no way to describe that using a single start, size, and stride. So there is no way to construct such a view.

如果您希望能够查看第二列而不是第二行,则可以按列优先(又名Fortran)的顺序构造数组:

If you want to be able to view every second column instead of every second row, you can construct your array in column-major aka Fortran order instead:

np.array(a, order='F')

然后它将被这样存储:

A1 B1 C1 A2 B2 C2 A3 B3 C3

这篇关于脾气暴躁的:视图vs通过切片复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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