micropython-ulab icon indicating copy to clipboard operation
micropython-ulab copied to clipboard

[FEATURE REQUEST] numpy.insert()

Open water5 opened this issue 3 years ago • 8 comments

https://numpy.org/doc/1.21/reference/generated/numpy.insert.html

b = np.array([[1, 2, 3], [4, 5, 6]])

array([[1, 2, 3], [4, 5, 6]])

np.insert(b, 1, [7, 8, 9])

array([1, 7, 8, 9, 2, 3, 4, 5, 6])

np.insert(b, 1, [7, 8, 9], axis = 0)

array([[1, 2, 3], [7, 8, 9], [4, 5, 6]])

water5 avatar Dec 19 '21 17:12 water5

@water5 Wouldn't this basically duplicate the functionality of concatenate? https://micropython-ulab.readthedocs.io/en/latest/ulab-ndarray.html?highlight=concatenate#concatenate

v923z avatar Jan 19 '22 06:01 v923z

But that can't specify where to insert, I consider numpy.append before post this request.

water5 avatar Jan 19 '22 19:01 water5

Obviously, you first have to split your original array into two with slicing (that is, where you specify where you want to insert the values), and then concatenate the first slice, the value, and the second slice.

a = array([1, 2, 3, 4, 5, 6])
value = array([10, 11])
concatenate(a[:3], value, a[3:])

v923z avatar Jan 19 '22 19:01 v923z

Append is similar

a = array([1, 2, 3, 4, 5, 6])
b = array([10, 20, 30])
c = zeros(len(a) + len(b))
c[:len(a)] = a
c[len(a):] = b

v923z avatar Jan 19 '22 19:01 v923z

On 2D array,

a = np.arange(25).reshape(5, 5)
a

array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]])

b = np.arange(25, 31)
b

array([25, 26, 27, 28, 29])

np.insert(a, 1, b, axis = 0)

array([[ 0, 1, 2, 3, 4], [25, 26, 27, 28, 29], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]])

np.insert(a, 1, b, axis = 1)

array([[ 0, 25, 1, 2, 3, 4], [ 5, 26, 6, 7, 8, 9], [10, 27, 11, 12, 13, 14], [15, 28, 16, 17, 18, 19], [20, 29, 21, 22, 23, 24]])

np.concatenate(a[ : 1], b, a[1 : ])

Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<__array_function__ internals>", line 180, in concatenate TypeError: only integer scalar arrays can be converted to a scalar index

water5 avatar Jan 19 '22 19:01 water5

a = array(range(25)).reshape((5,5))
b = np.arange(25, 30).reshape((1,5))
np.concatenate((a[:1], b, a[1:]))

v923z avatar Jan 19 '22 19:01 v923z

Right, that seems could implement most numpy.insert function. I close this issue directly, or make a snippet?

water5 avatar Jan 19 '22 20:01 water5

Right, that seems could implement most numpy.insert function. I close this issue directly, or make a snippet?

You could definitely write a small snippet, if you feel like it. In that case, add the snippet label to the issue, and keep it open till you are done, otherwise, close it.

v923z avatar Jan 19 '22 20:01 v923z