Code 1
arr = np.array([1, 2, 3])
arr2 = arr.view()
Code 2
arr = np.array([1, 2, 3])
arr2 = arr
Both of these snippets have the same functionality, so why do we actually need the view
method in NumPy if we can simply achieve the same result with code 2?
CodePudding user response:
Even without using the things view
lets you do, the semantics are different.
arr2 = arr
This assigns a reference to the original array to a different name. Any change you make to arr2
short of reassignment will show up when you access arr
.
arr2 = arr.view()
This creates a new array object that only shares data with the original. You can do something like arr2.shape = (3, 1, 1)
without affecting arr
at all.
At the same time, that's not what view
is generally used for. Let's say you wanted to look at the individual bytes that make up your integers. You would create a view with a different dtype:
arr2 = arr.view(np.uint8)
Or say you wanted to reinterpret your integers as big- instead of little-endian:
arr2 = arr.view('>i4')
Keep in mind that many other useful operations do this as well, like reshape
(same dtype, different shape), transpose
(same dtype, different strides), etc.
CodePudding user response:
as you can read in document
:
a.view(some_dtype) or a.view(dtype=some_dtype) constructs a view of the array’s memory with a different data-type. This can cause a reinterpretation of the bytes of memory. so you can create an array with different types like below:
>>> arr = np.array([1,2,3])
>>> arr2 = arr.view(dtype=np.int8)
>>> arr2
array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
0, 0], dtype=int8)
>>> arr2 = arr.view(dtype=np.int32)
array([1, 0, 2, 0, 3, 0], dtype=int32)
#You can change type and dtype like below
>>> arr2 = arr.view(dtype=np.int64, type=np.matrix)
>>> arr2
matrix([[1, 2, 3]])
If you write like below view
and assign
like same:
>>> arr2 = arr.view(dtype=np.int64)
>>> arr2.dtype
dtype('int64')
>>> arr3 = arr
>>> arr3.dtype
dtype('int64')