Insert values along the given axis before the given indices. Parameters ---------- arr : array_like Input array. obj : slice, int, array-like of ints or bools Object that defines the index or indices before which `values` is inserted. .. version
(arr, obj, values, axis=None)
| 5403 | |
| 5404 | @array_function_dispatch(_insert_dispatcher) |
| 5405 | def insert(arr, obj, values, axis=None): |
| 5406 | """ |
| 5407 | Insert values along the given axis before the given indices. |
| 5408 | |
| 5409 | Parameters |
| 5410 | ---------- |
| 5411 | arr : array_like |
| 5412 | Input array. |
| 5413 | obj : slice, int, array-like of ints or bools |
| 5414 | Object that defines the index or indices before which `values` is |
| 5415 | inserted. |
| 5416 | |
| 5417 | .. versionchanged:: 2.1.2 |
| 5418 | Boolean indices are now treated as a mask of elements to insert, |
| 5419 | rather than being cast to the integers 0 and 1. |
| 5420 | |
| 5421 | Support for multiple insertions when `obj` is a single scalar or a |
| 5422 | sequence with one element (similar to calling insert multiple |
| 5423 | times). |
| 5424 | values : array_like |
| 5425 | Values to insert into `arr`. If the type of `values` is different |
| 5426 | from that of `arr`, `values` is converted to the type of `arr`. |
| 5427 | `values` should be shaped so that ``arr[...,obj,...] = values`` |
| 5428 | is legal. |
| 5429 | axis : int, optional |
| 5430 | Axis along which to insert `values`. If `axis` is None then `arr` |
| 5431 | is flattened first. |
| 5432 | |
| 5433 | Returns |
| 5434 | ------- |
| 5435 | out : ndarray |
| 5436 | A copy of `arr` with `values` inserted. Note that `insert` |
| 5437 | does not occur in-place: a new array is returned. If |
| 5438 | `axis` is None, `out` is a flattened array. |
| 5439 | |
| 5440 | See Also |
| 5441 | -------- |
| 5442 | append : Append elements at the end of an array. |
| 5443 | concatenate : Join a sequence of arrays along an existing axis. |
| 5444 | delete : Delete elements from an array. |
| 5445 | |
| 5446 | Notes |
| 5447 | ----- |
| 5448 | Note that for higher dimensional inserts ``obj=0`` behaves very different |
| 5449 | from ``obj=[0]`` just like ``arr[:,0,:] = values`` is different from |
| 5450 | ``arr[:,[0],:] = values``. This is because of the difference between basic |
| 5451 | and advanced :ref:`indexing <basics.indexing>`. |
| 5452 | |
| 5453 | Examples |
| 5454 | -------- |
| 5455 | >>> import numpy as np |
| 5456 | >>> a = np.arange(6).reshape(3, 2) |
| 5457 | >>> a |
| 5458 | array([[0, 1], |
| 5459 | [2, 3], |
| 5460 | [4, 5]]) |
| 5461 | >>> np.insert(a, 1, 6) |
| 5462 | array([0, 6, 1, 2, 3, 4, 5]) |