forked from nipraxis/textbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumpy_transpose.Rmd
104 lines (84 loc) · 2.06 KB
/
numpy_transpose.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
---
jupyter:
jupytext:
text_representation:
extension: .Rmd
format_name: rmarkdown
format_version: '1.2'
jupytext_version: 1.11.5
---
$\newcommand{L}[1]{\| #1 \|}\newcommand{VL}[1]{\L{ \vec{#1} }}\newcommand{R}[1]{\operatorname{Re}\,(#1)}\newcommand{I}[1]{\operatorname{Im}\, (#1)}$
## `numpy.tranpose` for swapping axes
Numpy allows you to swap axes without costing anything in memory, and very
little in time.
The obvious axis swap is a 2D array transpose:
```{python}
import numpy as np
arr = np.reshape(np.arange(10), (5, 2))
arr
```
```{python}
arr.T
```
The `transpose` method - and the `np.tranpose` function does the same
thing as the `.T` attribute above:
```{python}
arr.transpose()
```
The advantage of `transpose` over the `.T` attribute is that is allows you
to move axes into any arbitrary order.
For example, let’s say you had a 3D array:
```{python}
arr = np.reshape(np.arange(24), (2, 3, 4))
arr
```
```{python}
arr.shape
```
```{python}
arr[:, :, 0]
```
`transpose` allows you to re-order these axes as you like. For example,
maybe you wanted to take the current last axis, and make it the first axis.
You pass `transpose` the order of the axes that you want:
```{python}
new_arr = arr.transpose(2, 0, 1)
```
```{python}
new_arr
```
```{python}
new_arr.shape
```
```{python}
new_arr[0, :, :]
```
Notice that the contents of the axis has not changed, just the position.
`new_arr[i, :, :]` is the same as `arr[:, :, i]` for any `i`.
<!-- vim:ft=rst -->
<!-- Course -->
<!-- BIC -->
<!-- Python distributions -->
<!-- Version control -->
<!-- Editors -->
<!-- Python and common libraries -->
<!-- IPython -->
<!-- Virtualenv and helpers -->
<!-- Pypi and packaging -->
<!-- Mac development -->
<!-- Windows development -->
<!-- Nipy and friends -->
<!-- FMRI datasets -->
<!-- Languages -->
<!-- Imaging software -->
<!-- Installation -->
<!-- Tutorials -->
<!-- MB tutorials -->
<!-- Ideas -->
<!-- Psych-214 -->
<!-- People -->
<!-- Licenses -->
<!-- Neuroimaging stuff -->
<!-- OpenFMRI projects -->
<!-- Unix -->
<!-- Substitutions -->