Issue
In Python I can append to an empty array like:
>>> a = []
>>> a.append([1,2,3])
>>> a.append([1,2,3])
>>> a
[[1, 2, 3], [1, 2, 3]]
How can I do the same in NumPy? np.append
flattens the array, unfortunately (and I need to have an empty array at the beginning).
Solution
OP intended to start with empty array. So, here's one approach using NumPy
In [2]: a = np.empty((0,3), int)
In [3]: a
Out[3]: array([], shape=(0L, 3L), dtype=int32)
In [4]: a = np.append(a, [[1,2,3]], axis=0)
In [5]: a
Out[5]: array([[1, 2, 3]])
In [6]: a = np.append(a, [[1,2,3]], axis=0)
In [7]: a
Out[7]:
array([[1, 2, 3],
[1, 2, 3]])
BUT, if you're appending in a large number of loops. It's faster to append list first and convert to array than appending NumPy arrays.
In [8]: %%timeit
...: list_a = []
...: for _ in xrange(10000):
...: list_a.append([1, 2, 3])
...: list_a = np.asarray(list_a)
...:
100 loops, best of 3: 5.95 ms per loop
In [9]: %%timeit
....: arr_a = np.empty((0, 3), int)
....: for _ in xrange(10000):
....: arr_a = np.append(arr_a, np.array([[1,2,3]]), 0)
....:
10 loops, best of 3: 110 ms per loop
For Python 3.x, use range()
instead of the now-deprecated xrange()
.
Answered By - Zero
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.