回答編集履歴
2
追記
answer
CHANGED
@@ -54,6 +54,10 @@
|
|
54
54
|
|
55
55
|
```
|
56
56
|
|
57
|
-
https://
|
57
|
+
https://stackoverflow.com/questions/4389517/in-place-type-conversion-of-a-numpy-array
|
58
58
|
|
59
|
-
|
59
|
+
リファレンスにはけっこう怖い記述があるので、必ずしもいい方法ではないかもしれません。
|
60
|
+
|
61
|
+
> For a.view(some_dtype), if some_dtype has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of a (shown by print(a)). It also depends on exactly how a is stored in memory. Therefore if a is C-ordered versus fortran-ordered, versus defined as a slice or transpose, etc., the view may give different results.
|
62
|
+
|
63
|
+
> https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.view.html
|
1
追記
answer
CHANGED
@@ -6,4 +6,54 @@
|
|
6
6
|
|
7
7
|
とも書けます。ただし、内部的には同じか、へたするとかえって遅くなる程度ですね。
|
8
8
|
|
9
|
-
質問文のやり方はnumpyを使うのであれば最良に近いと思います。同じメモリ領域を読み替えたりするのは難しいので、そこは諦めるのが前提になります。
|
9
|
+
質問文のやり方はnumpyを使うのであれば最良に近いと思います。同じメモリ領域を読み替えたりするのは難しいので、そこは諦めるのが前提になります。
|
10
|
+
|
11
|
+
|
12
|
+
### 追記
|
13
|
+
すみません、viewで型指定すればできそうです。ただしread-onlyになりそう。
|
14
|
+
|
15
|
+
```python
|
16
|
+
>>> import numpy as np
|
17
|
+
>>> a = np.random.randint(100, 1000, (4, 3), dtype=np.uint32)
|
18
|
+
>>> b = np.frombuffer(a.tobytes(), dtype=np.uint8).reshape([4, 3, 4])
|
19
|
+
>>> b
|
20
|
+
array([[[ 67, 1, 0, 0],
|
21
|
+
[148, 1, 0, 0],
|
22
|
+
[242, 1, 0, 0]],
|
23
|
+
|
24
|
+
[[ 55, 1, 0, 0],
|
25
|
+
[138, 0, 0, 0],
|
26
|
+
[ 80, 3, 0, 0]],
|
27
|
+
|
28
|
+
[[ 66, 1, 0, 0],
|
29
|
+
[ 71, 3, 0, 0],
|
30
|
+
[100, 0, 0, 0]],
|
31
|
+
|
32
|
+
[[ 3, 3, 0, 0],
|
33
|
+
[ 84, 3, 0, 0],
|
34
|
+
[134, 2, 0, 0]]], dtype=uint8)
|
35
|
+
>>> b2 = a.view(np.uint8).reshape(4, 3, 4)
|
36
|
+
>>> b2
|
37
|
+
array([[[ 67, 1, 0, 0],
|
38
|
+
[148, 1, 0, 0],
|
39
|
+
[242, 1, 0, 0]],
|
40
|
+
|
41
|
+
[[ 55, 1, 0, 0],
|
42
|
+
[138, 0, 0, 0],
|
43
|
+
[ 80, 3, 0, 0]],
|
44
|
+
|
45
|
+
[[ 66, 1, 0, 0],
|
46
|
+
[ 71, 3, 0, 0],
|
47
|
+
[100, 0, 0, 0]],
|
48
|
+
|
49
|
+
[[ 3, 3, 0, 0],
|
50
|
+
[ 84, 3, 0, 0],
|
51
|
+
[134, 2, 0, 0]]], dtype=uint8)
|
52
|
+
>>> (b == b2).all()
|
53
|
+
True
|
54
|
+
|
55
|
+
```
|
56
|
+
|
57
|
+
https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.view.html
|
58
|
+
|
59
|
+
https://stackoverflow.com/questions/4389517/in-place-type-conversion-of-a-numpy-array
|