copy和view

copy和view

1
2
import numpy as np
x = np.array([1, 2, 3, 4, 5],dtype = float)

切片:

1
2
z = x[0:5]
print(z)

[1 2 3 4 5]

花哨索引:

1
2
y = x[[0, 1, 2, 3, 4]]
print(y)

[1 2 3 4 5]

布尔索引

1
2
w = x[[True, True, True, False, False]]
print(w)

[1 2 3]

切片返回的是原数组的一个view,花哨索引和布尔索引返回的是原数组的一个copy:

1
2
3
4
5
6
7
8
x[0] = 100
print("直接改变原数组:x = ", x)
z[0:5][0] = 200
print("改变切片后会影响原数组:x = ", x)
y[0] = 300
print("改变花哨索引后不影响原数组:x = ", x)
w[0] = 400
print('改变布尔索引后不影响原数组:x = ', x)

直接改变原数组:

x = [100 2 3 4 5]

改变切片后会影响原数组:x = [200 2 3 4 5]

改变花哨索引后不影响原数组:x = [200 2 3 4 5]

改变布尔索引后不影响原数组:x = [200 2 3 4 5]

然而虽然改变切片是原数组的一个view,但是id却不同...

1
2
3
z1 = x[0:5]
z2 = x[0:5]
print(id(z1) - id(z2))

43565216

np.where()!

1
2
3
x = np.array([1,2,3,4,5])
index = np.where(x>2)
print(index)

(array([2, 3, 4], dtype=int64),)

要改变原数组的值...A不可以,B可以...

A

1
2
for i in x[index[0]]:
i = 100print(x)

[1 2 3 4 5]

B

1
2
for i in index[0]:
x[i] = 100print(x)

[ 1 2 100 100 100]