如何使NumPy数组成为只读
让我们讨论一下如何使NumPy数组变得不可改变,即不能被重写或不能被改变。这可以通过设置NumPy数组的可写标志为false来实现。
语法:
array.flags.writable=False
这就把可写标志设置为假,因此数组就成为不可变的,即只读的。请看下面的例子
示例:
import numpy as np
a = np.zeros(11)
print("Before any change ")
print(a)
a[1] = 2
print("Before after first change ")
print(a)
a.setflags(write=False)
print("After making array immutable on attempting second change ")
a[1] = 7
输出:
Before any change
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
Before after first change
[0. 2. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
After making array immutable on attempting second change
Traceback (most recent call last):
File "gfg9.py", line 11, in <module>
a[1]=7
ValueError: assignment destination is read-only