为什么数组[:]没有复制数组?

[英]Why isn't array[:] copying the array?


I recently found a solution to a problem I find bizarre and would like to better understand the situation. The problem involves over-writing values at specified indices of an array.

我最近找到了一个问题的解决方案,我觉得很奇怪,并希望更好地了解情况。该问题涉及在数组的指定索引处重写值。

import numpy as np

# create array to overwrite
mask = np.ones(10)

# first set of index-value pairs
idx_1 = [0, 3, 4]
val_1 = [100, 200, 300]

# second set of index-value pairs
idx_2 = [1, 5, 6]
val_2 = [250, 505, 650]

# third set of index-value pairs
idx_3 = [7, 8, 9]
val_3 = [900, 800, 700]

def overwrite_mask(mask, indices, values):
    """ This function overwrites elements in mask with values at indices. """
    mask[indices] = values
    return mask

# incorrect
# res_1 = overwrite_mask(mask[:], idx_1, val_1)
# res_2 = overwrite_mask(mask[:], idx_2, val_2)
# res_3 = overwrite_mask(mask[:], idx_3, val_3)
# >> [ 100.  250.    1.  200.  300.  505.  650.  900.  800.  700.]
# >> [ 100.  250.    1.  200.  300.  505.  650.  900.  800.  700.]
# >> [ 100.  250.    1.  200.  300.  505.  650.  900.  800.  700.]

# correct
res_1 = overwrite_mask(mask.copy(), idx_1, val_1)
res_2 = overwrite_mask(mask.copy(), idx_2, val_2)
res_3 = overwrite_mask(mask.copy(), idx_3, val_3)
# [ 100.    1.    1.  200.  300.    1.    1.    1.    1.    1.]
# [   1.  250.    1.    1.    1.  505.  650.    1.    1.    1.]
# [   1.    1.    1.    1.    1.    1.    1.  900.  800.  700.] 

I was under the impression that [:] applied after an array produced an exact copy of the array. But it seems as though [:] isn't working as it should in this context.

我的印象是在数组生成完整数组副本后应用[:]。但似乎[:]在这种情况下不能正常工作。

What is happening here?

这里发生了什么?

1 个解决方案

#1


3  

I was under the impression that [:] applied after an array produced an exact copy of the array.

我的印象是在数组生成完整数组副本后应用[:]。

That's wrong. The [:] applied to instances of Python types like list, str, ... will return a "shallow" copy but that doesn't mean the same applies to NumPy arrays.

那是错的。应用于像list,str,...等Python类型实例的[:]将返回一个“浅”副本,但这并不意味着同样适用于NumPy数组。

In fact NumPy will always return views when "basic slicing" is used. Because [:] is basic slicing it will never copy the array. See the documentation:

事实上,当使用“基本切片”时,NumPy将始终返回视图。因为[:]是基本切片,所以永远不会复制数组。查看文档:

All arrays generated by basic slicing are always views of the original array.

通过基本切片生成的所有数组始终是原始数组的视图。

关注微信公众号

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2017/11/30/ef44e444803bac38472f44a7c0ecda1.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com