Insert values along the given axis before the given indices. Parameters ---------- arr : array_like Input array. obj : int, slice or sequence of ints Object that defines the index or indices before which `values` is inserted. .. versionadded:: 1
(arr, obj, values, axis=None)
| 5368 | |
| 5369 | @array_function_dispatch(_insert_dispatcher) |
| 5370 | def insert(arr, obj, values, axis=None): |
| 5371 | """ |
| 5372 | Insert values along the given axis before the given indices. |
| 5373 | |
| 5374 | Parameters |
| 5375 | ---------- |
| 5376 | arr : array_like |
| 5377 | Input array. |
| 5378 | obj : int, slice or sequence of ints |
| 5379 | Object that defines the index or indices before which `values` is |
| 5380 | inserted. |
| 5381 | |
| 5382 | .. versionadded:: 1.8.0 |
| 5383 | |
| 5384 | Support for multiple insertions when `obj` is a single scalar or a |
| 5385 | sequence with one element (similar to calling insert multiple |
| 5386 | times). |
| 5387 | values : array_like |
| 5388 | Values to insert into `arr`. If the type of `values` is different |
| 5389 | from that of `arr`, `values` is converted to the type of `arr`. |
| 5390 | `values` should be shaped so that ``arr[...,obj,...] = values`` |
| 5391 | is legal. |
| 5392 | axis : int, optional |
| 5393 | Axis along which to insert `values`. If `axis` is None then `arr` |
| 5394 | is flattened first. |
| 5395 | |
| 5396 | Returns |
| 5397 | ------- |
| 5398 | out : ndarray |
| 5399 | A copy of `arr` with `values` inserted. Note that `insert` |
| 5400 | does not occur in-place: a new array is returned. If |
| 5401 | `axis` is None, `out` is a flattened array. |
| 5402 | |
| 5403 | See Also |
| 5404 | -------- |
| 5405 | append : Append elements at the end of an array. |
| 5406 | concatenate : Join a sequence of arrays along an existing axis. |
| 5407 | delete : Delete elements from an array. |
| 5408 | |
| 5409 | Notes |
| 5410 | ----- |
| 5411 | Note that for higher dimensional inserts ``obj=0`` behaves very different |
| 5412 | from ``obj=[0]`` just like ``arr[:,0,:] = values`` is different from |
| 5413 | ``arr[:,[0],:] = values``. |
| 5414 | |
| 5415 | Examples |
| 5416 | -------- |
| 5417 | >>> a = np.array([[1, 1], [2, 2], [3, 3]]) |
| 5418 | >>> a |
| 5419 | array([[1, 1], |
| 5420 | [2, 2], |
| 5421 | [3, 3]]) |
| 5422 | >>> np.insert(a, 1, 5) |
| 5423 | array([1, 5, 1, ..., 2, 3, 3]) |
| 5424 | >>> np.insert(a, 1, 5, axis=1) |
| 5425 | array([[1, 5, 1], |
| 5426 | [2, 5, 2], |
| 5427 | [3, 5, 3]]) |