forked from cirosantilli/python-cheat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumpy_cheat.py
More file actions
executable file
·272 lines (220 loc) · 5.95 KB
/
numpy_cheat.py
File metadata and controls
executable file
·272 lines (220 loc) · 5.95 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
#!/usr/bin/env python
import StringIO
import numpy as np
def norm2(a):
"""
Mean squared norm.
"""
return np.linalg.norm(a) / a.size
def dist2(a, a2):
return norm2(a - a2)
def array_equal(a, a2, err=10e-6, dist=dist2):
"""
True iff two np.arrays are equal within a given `err` precision for given `dist` distance.
"""
return dist(a, a2) < err
if '## ndarray':
if '## slicing':
x = np.array([
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
])
assert np.array_equal(
x[:, 0],
[0, 3, 6]
)
assert np.array_equal(
x[0, :],
[0, 1, 2]
)
assert np.array_equal(
x[0:3:2, 0:3:2],
[
[0, 2],
[6, 8],
]
)
# Pairwise list!
assert np.array_equal(
x[[0, 1], [1, 2]],
[1, 5]
)
# Submtraix.
assert np.array_equal(
x[[[0], [1]], [1, 2]],
[
[1, 2],
[4, 5],
]
)
# Transposed.
assert np.array_equal(
x[[0, 1], [[1], [2]]],
[
[1, 4],
[2, 5],
]
)
if '## Split by value of column':
"""
http://stackoverflow.com/questions/21757680/python-separate-matrix-by-column-values
"""
a = np.array([
[0, 1, 1],
[1, 1, -1],
[0, 2, 2],
[1, 2, -2],
[0, 3, 3],
[1, 3, -3],
])
aa = np.array([
[
[0, 1, 1],
[0, 2, 2],
[0, 3, 3],
],
[
[1, 1, -1],
[1, 2, -2],
[1, 3, -3],
],
])
if '## Known keys':
assert np.array_equal(
a[a[:, 0] == 0, :],
np.array([
[0, 1, 1],
[0, 2, 2],
[0, 3, 3],
])
)
assert np.array_equal(
a[a[:, 0] == 1, :],
np.array([
[1, 1, -1],
[1, 2, -2],
[1, 3, -3],
])
)
if '## Unknown values':
keys = list(set(a[:, 0]))
for key in keys:
assert np.array_equal(
a[a[:, 0] == key, :],
aa[key],
)
if '## sum':
# Over all elements.
assert array_equal(
np.sum([
[0, 1],
[2, 3]
]),
6
)
# Some dimensions only.
assert array_equal(
np.sum([[0, 1], [2, 3]], axis = 0),
[2, 4]
)
assert array_equal(
np.sum([[0, 1], [2, 3]], axis = 1),
[1, 5]
)
if '## Structured array ## dtype':
"""
Using dtype changes the form of the array.
It becomes a list of tuples.
Insane.
Types specifiers at: http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html
"""
x = np.array([
(0, 1),
(2, 3),
],
dtype=[
('a', 'i4'),
('b', 'f4')
]
)
assert type(x) == np.ndarray
assert type(x[0]) == np.void
assert type(x[0][0]) == np.int32
assert type(x[0][1]) == np.float32
assert type(x[1][0]) == np.int32
assert type(x[1][1]) == np.float32
assert np.array_equal(x['a'], [0, 2])
assert np.array_equal(x['b'], [1.0, 3.0])
assert x[0]['a'] == 0
# Does not work with arrays here. Insane.
# x = np.array([
# [0, 1],
# [2, 3],
# ],
# dtype=[('a','i4'),('b','f4')]
# )
# Cannot use two indexes.
try:
assert x[0, 0] == 1
except IndexError:
pass
else:
assert False
# print type(a[0])
# assert a[0] == (1, 2.0, 'ab')
if '## file io':
# TODO: examples
"""
a = np.zeros((2, 3))
# Space separated.
np.savetxt("a.tmp", a)
np.savetxt("b.tmp", delimiter = ", ")
# single width format
np.savetxt("c.tmp", delimiter = 3)
# multi width format
np.savetxt("d.tmp", delimiter = (4, 3, 2))
# strip trailing/starting whitespace
np.savetxt("e.tmp", autostrip = True)
# stop reading line when # is found
np.savetxt("f.tmp", comments = '# ')
# skip first line, and last two lines
np.savetxt("g.tmp", skip_header = 1, skip_footer = 2)
# only use first and last columns
np.savetxt("h.tmp", usecols = (0, -1))
# same, give names
np.savetxt("b.tmp", names = "a, b, c", usecols = ("a", "c"))
b = genfromtxt("a.tmp")
b = loadtxt("a.tmp")
"""
if 'loadtxt':
assert np.array_equal(
np.loadtxt(StringIO.StringIO("0 1\n2 3\n")),
[
[0.0, 1.0],
[2.0, 3.0],
]
)
# Dtype works like for the array constructor.
x = np.loadtxt(
StringIO.StringIO("0 1\n2 3\n"),
dtype=[('a', 'i4'), ('b', 'f4')]
)
assert type(x) == np.ndarray
assert type(x[0]) == np.void
assert type(x[0][0]) == np.int32
assert type(x[0][1]) == np.float32
assert type(x[1][0]) == np.int32
assert type(x[1][1]) == np.float32
# usecols
assert array_equal(
np.loadtxt(
StringIO.StringIO("0 1\n2 3\n"),
usecols=(1,)
),
[
[1.0, 3.0],
]
)
# It is slow for large files:
# http://stackoverflow.com/questions/18259393/numpy-loading-csv-too-slow-compared-to-matlab