flopscope.numpy.insert
fnp.insert(arr, obj, values, axis=None)[flopscope source][numpy source]
Insert values along the given axis before the given indices.
Adapted from NumPy docs np.insert
Insert values along axis before given indices. Cost: numel(values).
Parameters
- arr:array_like
Input array.
- obj:slice, int, array-like of ints or bools
Object that defines the index or indices before which
valuesis inserted.Changed in version 2.1.2.Support for multiple insertions when
objis a single scalar or a sequence with one element (similar to calling insert multiple times).- values:array_like
Values to insert into
arr. If the type ofvaluesis different from that ofarr,valuesis converted to the type ofarr.valuesshould be shaped so thatarr[...,obj,...] = valuesis legal.- axis:int, optional
Axis along which to insert
values. Ifaxisis None thenarris flattened first.
Returns
- out:ndarray
A copy of
arrwithvaluesinserted. Note that insert does not occur in-place: a new array is returned. Ifaxisis None,outis a flattened array.
See also
- we.flops.append Append elements at the end of an array.
- we.flops.concatenate Join a sequence of arrays along an existing axis.
- we.flops.delete Delete elements from an array.
Notes
Note that for higher dimensional inserts obj=0 behaves very different
from obj=[0] just like arr[:,0,:] = values is different from
arr[:,[0],:] = values. This is because of the difference between basic
and advanced indexing.
Examples
>>> import flopscope.numpy as fnp
>>> a = flops.arange(6).reshape(3, 2)
>>> a
array([[0, 1],
[2, 3],
[4, 5]])
>>> flops.insert(a, 1, 6)
array([0, 6, 1, 2, 3, 4, 5])
>>> flops.insert(a, 1, 6, axis=1)
array([[0, 6, 1],
[2, 6, 3],
[4, 6, 5]])Difference between sequence and scalars,
showing how obj=[1] behaves different from obj=1:
>>> flops.insert(a, [1], [[7],[8],[9]], axis=1)
array([[0, 7, 1],
[2, 8, 3],
[4, 9, 5]])
>>> flops.insert(a, 1, [[7],[8],[9]], axis=1)
array([[0, 7, 8, 9, 1],
[2, 7, 8, 9, 3],
[4, 7, 8, 9, 5]])
>>> flops.array_equal(flops.insert(a, 1, [7, 8, 9], axis=1),
... flops.insert(a, [1], [[7],[8],[9]], axis=1))
True>>> b = a.flatten()
>>> b
array([0, 1, 2, 3, 4, 5])
>>> flops.insert(b, [2, 2], [6, 7])
array([0, 1, 6, 7, 2, 3, 4, 5])>>> flops.insert(b, slice(2, 4), [7, 8])
array([0, 1, 7, 2, 8, 3, 4, 5])>>> flops.insert(b, [2, 2], [7.13, False]) # type casting
array([0, 1, 7, 0, 2, 3, 4, 5])>>> x = flops.arange(8).reshape(2, 4)
>>> idx = (1, 3)
>>> flops.insert(x, idx, 999, axis=1)
array([[ 0, 999, 1, 2, 999, 3],
[ 4, 999, 5, 6, 999, 7]])