_add_newdocs.pyc
1 o 2 [��c�K � @ s� d Z ddlmZ ddlmZ eddd� eddd� eddd� eddd � eddd 3 � eddd� eddd � eddd� eddd� eddd� eddd� eddd� eddd� eddd� eddd� eddd� eddd� eddd� eddd� eddd� eddd� eddd� eddd� eddd � eddd!� eddd"� ed#d$d%�d&e�� ed#d'd(�d&e�� ed#d)d*�d&e�� ed#d+d,�d&e�� ed#d-d.�d&e�� ed#d/d0�d&e�� ed#d1d2� ed#d3d4�d&e�� ed#d5d6� ed#d7d8�d&e�� ed#d9d:� ed#d;d<�d&e�� ed#d=d>�d&e�� ed#d?d@�d&e�� ed#dAdB� eddCdD� ed#dEdF� ed#dGdH�d&e�� ed#dIdJ� ed#dKdL� ed#dMdN� ed#dOdP� ed#dQdR� ed#dSdT� ed#dUdV� ed#dUdW� ed#dUdX� ed#dUdY� ed#dUdZ� ed#dUd[� ed#dUd\� ed#dUd]� ed#dUd^� ed#dUd_� ed#dUd`� ed#dUda� ed#dUdb� ed#dUdc� ed#dUdd� ed#dUde� ed#dUdf� ed#dUdg� ed#dUdh� ed#dUdi� ed#dUdj� ed#dUdk� ed#dUdl� ed#dUdm� ed#dUdn� ed#dUdo� ed#dUdp� ed#dUdq� ed#dUdr� ed#dUds� ed#dUdt� ed#dUdu� ed#dUdv� ed#dUdw� ed#dUdx� ed#dUdy� ed#dUdz� ed#dUd{� ed#dUd|� ed#dUd}� ed#dUd~� ed#dUd� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed#dUd�� ed�d�d�� ed�d�d�� ed�d�d�� ed#d�d�� ed�d�d�� ed#d�d�� ed#d�d�� ed#d�d�� ed#d�d�� ed�d�d�� edd�dà edd�dă edd�dŃ edd�dƃ edd�dǃ edd�dȃ edd�dɃ edd�dʃ edd�d˃ edd�d̃ edd�d̓ edd�d edd�dσ edd�dЃ edd�dу edd�d҃ ed#d�dԃ ed#d�dՃ ed#d�dփ ed#d�d׃ ed#d�d ed#d�dك ed#d�dڃ ed#d�dۃ ed#d�d܃ ed#d�d݃ ed#d�dރ ed#d�d߃ ed#d�d�� ed#d�d� ed#d�d� ed#d�d� ed#d�d� ed#d�d� ed#d�d� ed#d�d� ed#d�d� ed#d�d� ed#d�d� ed#d�d� ed#d�d� ed#d�d� ed#d�d� ed#d�d� ed#d�d�� ed#d�d� ed#d�d� ed#d�d� ed#d�d�� ed#d�d�� ed�d�d�� �dVd�d��Zed�d�ed��d �d�� ed�d�e�d�d �d�� ed�d��d� ed�d��d� ed�d��d� ed�d��d� ed�d��d� ed�d��d� ed�d��d � ed�d��d 4 � ed�d��d� ed�d��d� ed�d��d � ed�d��d� ed�d�e�d�� ed�d�e�d�� ed�d�e�d�� ed�d�e�d�� ed�d�e�d�� ed�d�e�d�� ed�d�e�d�� ed�d�e�d�� ed�d�e�d�� ed�d�e�d�� ed�d�e�d�� ed�d�e�d�� ed�d�e�d�� ed�d�e�d�� ed�d�e�d�� ed�d�e�d�� ed�d�e�d�� ed�d�e�d �� ed�d�e�d!�� ed�d�e�d"�� ed�d�e�d#�� ed�d�e�d$�� ed�d�e�d%�� ed�d�e�d&�� ed�d�e�d'�� ed�d��d(� ed�d�e�d)�� ed�d�e�d*�� ed�d�e�d+�� ed�d�e�d,�� ed�d�e�d-�� ed�d�e�d.�� ed�d�e�d/�� ed�d�e�d0�� ed�d�e�d1�� ed�d�e�d2�� ed�d�e�d3�� ed�d�e�d4�� ed�d�e�d5�� ed�d�e�d6�� ed�d�e�d7�� ed�d�e�d8�� ed�d�e�d9�� ed�d�e�d:�� ed�d�e�d;�� ed�d�e�d<�� ed�d�e�d=�� ed�d�e�d>�� ed�d�e�d?�� ed�d�e�d@�� ed�d�e�dA�� ed��dB�dC� ed��dB�dD� ed��dE�dF� ed��dG�dH� ed��dI�dJ� ed��dK�dL� ed��dM�dN� ed��dO�dP� ed��dQ�dR� ed��dS�dT� �dUS (W ae 5 This is only meant to add docs to objects defined in C-extension modules. 6 The purpose is to allow easier editing of the docstrings without 7 requiring a re-compile. 8 9 NOTE: Many of the methods of ndarray have corresponding functions. 10 If you update these docstrings, please keep also the ones in 11 core/fromnumeric.py, core/defmatrix.py up-to-date. 12 13 � )� 14 add_newdoc)�array_function_like_docz 15 numpy.core�flatitera� 16 Flat iterator object to iterate over arrays. 17 18 A `flatiter` iterator is returned by ``x.flat`` for any array `x`. 19 It allows iterating over the array as if it were a 1-D array, 20 either in a for-loop or by calling its `next` method. 21 22 Iteration is done in row-major, C-style order (the last 23 index varying the fastest). The iterator can also be indexed using 24 basic slicing or advanced indexing. 25 26 See Also 27 -------- 28 ndarray.flat : Return a flat iterator over an array. 29 ndarray.flatten : Returns a flattened copy of an array. 30 31 Notes 32 ----- 33 A `flatiter` iterator can not be constructed directly from Python code 34 by calling the `flatiter` constructor. 35 36 Examples 37 -------- 38 >>> x = np.arange(6).reshape(2, 3) 39 >>> fl = x.flat 40 >>> type(fl) 41 <class 'numpy.flatiter'> 42 >>> for item in fl: 43 ... print(item) 44 ... 45 0 46 1 47 2 48 3 49 4 50 5 51 52 >>> fl[2:4] 53 array([2, 3]) 54 55 )�basez� 56 A reference to the array that is iterated over. 57 58 Examples 59 -------- 60 >>> x = np.arange(5) 61 >>> fl = x.flat 62 >>> fl.base is x 63 True 64 65 )�coordsz� 66 An N-dimensional tuple of current coordinates. 67 68 Examples 69 -------- 70 >>> x = np.arange(6).reshape(2, 3) 71 >>> fl = x.flat 72 >>> fl.coords 73 (0, 0) 74 >>> next(fl) 75 0 76 >>> fl.coords 77 (0, 1) 78 79 )�indexz� 80 Current flat index into the array. 81 82 Examples 83 -------- 84 >>> x = np.arange(6).reshape(2, 3) 85 >>> fl = x.flat 86 >>> fl.index 87 0 88 >>> next(fl) 89 0 90 >>> fl.index 91 1 92 93 )� __array__z2__array__(type=None) Get array from iterator 94 95 )�copyz� 96 copy() 97 98 Get a copy of the iterator as a 1-D array. 99 100 Examples 101 -------- 102 >>> x = np.arange(6).reshape(2, 3) 103 >>> x 104 array([[0, 1, 2], 105 [3, 4, 5]]) 106 >>> fl = x.flat 107 >>> fl.copy() 108 array([0, 1, 2, 3, 4, 5]) 109 110 �nditeraY1 111 nditer(op, flags=None, op_flags=None, op_dtypes=None, order='K', casting='safe', op_axes=None, itershape=None, buffersize=0) 112 113 Efficient multi-dimensional iterator object to iterate over arrays. 114 To get started using this object, see the 115 :ref:`introductory guide to array iteration <arrays.nditer>`. 116 117 Parameters 118 ---------- 119 op : ndarray or sequence of array_like 120 The array(s) to iterate over. 121 122 flags : sequence of str, optional 123 Flags to control the behavior of the iterator. 124 125 * ``buffered`` enables buffering when required. 126 * ``c_index`` causes a C-order index to be tracked. 127 * ``f_index`` causes a Fortran-order index to be tracked. 128 * ``multi_index`` causes a multi-index, or a tuple of indices 129 with one per iteration dimension, to be tracked. 130 * ``common_dtype`` causes all the operands to be converted to 131 a common data type, with copying or buffering as necessary. 132 * ``copy_if_overlap`` causes the iterator to determine if read 133 operands have overlap with write operands, and make temporary 134 copies as necessary to avoid overlap. False positives (needless 135 copying) are possible in some cases. 136 * ``delay_bufalloc`` delays allocation of the buffers until 137 a reset() call is made. Allows ``allocate`` operands to 138 be initialized before their values are copied into the buffers. 139 * ``external_loop`` causes the ``values`` given to be 140 one-dimensional arrays with multiple values instead of 141 zero-dimensional arrays. 142 * ``grow_inner`` allows the ``value`` array sizes to be made 143 larger than the buffer size when both ``buffered`` and 144 ``external_loop`` is used. 145 * ``ranged`` allows the iterator to be restricted to a sub-range 146 of the iterindex values. 147 * ``refs_ok`` enables iteration of reference types, such as 148 object arrays. 149 * ``reduce_ok`` enables iteration of ``readwrite`` operands 150 which are broadcasted, also known as reduction operands. 151 * ``zerosize_ok`` allows `itersize` to be zero. 152 op_flags : list of list of str, optional 153 This is a list of flags for each operand. At minimum, one of 154 ``readonly``, ``readwrite``, or ``writeonly`` must be specified. 155 156 * ``readonly`` indicates the operand will only be read from. 157 * ``readwrite`` indicates the operand will be read from and written to. 158 * ``writeonly`` indicates the operand will only be written to. 159 * ``no_broadcast`` prevents the operand from being broadcasted. 160 * ``contig`` forces the operand data to be contiguous. 161 * ``aligned`` forces the operand data to be aligned. 162 * ``nbo`` forces the operand data to be in native byte order. 163 * ``copy`` allows a temporary read-only copy if required. 164 * ``updateifcopy`` allows a temporary read-write copy if required. 165 * ``allocate`` causes the array to be allocated if it is None 166 in the ``op`` parameter. 167 * ``no_subtype`` prevents an ``allocate`` operand from using a subtype. 168 * ``arraymask`` indicates that this operand is the mask to use 169 for selecting elements when writing to operands with the 170 'writemasked' flag set. The iterator does not enforce this, 171 but when writing from a buffer back to the array, it only 172 copies those elements indicated by this mask. 173 * ``writemasked`` indicates that only elements where the chosen 174 ``arraymask`` operand is True will be written to. 175 * ``overlap_assume_elementwise`` can be used to mark operands that are 176 accessed only in the iterator order, to allow less conservative 177 copying when ``copy_if_overlap`` is present. 178 op_dtypes : dtype or tuple of dtype(s), optional 179 The required data type(s) of the operands. If copying or buffering 180 is enabled, the data will be converted to/from their original types. 181 order : {'C', 'F', 'A', 'K'}, optional 182 Controls the iteration order. 'C' means C order, 'F' means 183 Fortran order, 'A' means 'F' order if all the arrays are Fortran 184 contiguous, 'C' order otherwise, and 'K' means as close to the 185 order the array elements appear in memory as possible. This also 186 affects the element memory order of ``allocate`` operands, as they 187 are allocated to be compatible with iteration order. 188 Default is 'K'. 189 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional 190 Controls what kind of data casting may occur when making a copy 191 or buffering. Setting this to 'unsafe' is not recommended, 192 as it can adversely affect accumulations. 193 194 * 'no' means the data types should not be cast at all. 195 * 'equiv' means only byte-order changes are allowed. 196 * 'safe' means only casts which can preserve values are allowed. 197 * 'same_kind' means only safe casts or casts within a kind, 198 like float64 to float32, are allowed. 199 * 'unsafe' means any data conversions may be done. 200 op_axes : list of list of ints, optional 201 If provided, is a list of ints or None for each operands. 202 The list of axes for an operand is a mapping from the dimensions 203 of the iterator to the dimensions of the operand. A value of 204 -1 can be placed for entries, causing that dimension to be 205 treated as `newaxis`. 206 itershape : tuple of ints, optional 207 The desired shape of the iterator. This allows ``allocate`` operands 208 with a dimension mapped by op_axes not corresponding to a dimension 209 of a different operand to get a value not equal to 1 for that 210 dimension. 211 buffersize : int, optional 212 When buffering is enabled, controls the size of the temporary 213 buffers. Set to 0 for the default value. 214 215 Attributes 216 ---------- 217 dtypes : tuple of dtype(s) 218 The data types of the values provided in `value`. This may be 219 different from the operand data types if buffering is enabled. 220 Valid only before the iterator is closed. 221 finished : bool 222 Whether the iteration over the operands is finished or not. 223 has_delayed_bufalloc : bool 224 If True, the iterator was created with the ``delay_bufalloc`` flag, 225 and no reset() function was called on it yet. 226 has_index : bool 227 If True, the iterator was created with either the ``c_index`` or 228 the ``f_index`` flag, and the property `index` can be used to 229 retrieve it. 230 has_multi_index : bool 231 If True, the iterator was created with the ``multi_index`` flag, 232 and the property `multi_index` can be used to retrieve it. 233 index 234 When the ``c_index`` or ``f_index`` flag was used, this property 235 provides access to the index. Raises a ValueError if accessed 236 and ``has_index`` is False. 237 iterationneedsapi : bool 238 Whether iteration requires access to the Python API, for example 239 if one of the operands is an object array. 240 iterindex : int 241 An index which matches the order of iteration. 242 itersize : int 243 Size of the iterator. 244 itviews 245 Structured view(s) of `operands` in memory, matching the reordered 246 and optimized iterator access pattern. Valid only before the iterator 247 is closed. 248 multi_index 249 When the ``multi_index`` flag was used, this property 250 provides access to the index. Raises a ValueError if accessed 251 accessed and ``has_multi_index`` is False. 252 ndim : int 253 The dimensions of the iterator. 254 nop : int 255 The number of iterator operands. 256 operands : tuple of operand(s) 257 The array(s) to be iterated over. Valid only before the iterator is 258 closed. 259 shape : tuple of ints 260 Shape tuple, the shape of the iterator. 261 value 262 Value of ``operands`` at current iteration. Normally, this is a 263 tuple of array scalars, but if the flag ``external_loop`` is used, 264 it is a tuple of one dimensional arrays. 265 266 Notes 267 ----- 268 `nditer` supersedes `flatiter`. The iterator implementation behind 269 `nditer` is also exposed by the NumPy C API. 270 271 The Python exposure supplies two iteration interfaces, one which follows 272 the Python iterator protocol, and another which mirrors the C-style 273 do-while pattern. The native Python approach is better in most cases, but 274 if you need the coordinates or index of an iterator, use the C-style pattern. 275 276 Examples 277 -------- 278 Here is how we might write an ``iter_add`` function, using the 279 Python iterator protocol: 280 281 >>> def iter_add_py(x, y, out=None): 282 ... addop = np.add 283 ... it = np.nditer([x, y, out], [], 284 ... [['readonly'], ['readonly'], ['writeonly','allocate']]) 285 ... with it: 286 ... for (a, b, c) in it: 287 ... addop(a, b, out=c) 288 ... return it.operands[2] 289 290 Here is the same function, but following the C-style pattern: 291 292 >>> def iter_add(x, y, out=None): 293 ... addop = np.add 294 ... it = np.nditer([x, y, out], [], 295 ... [['readonly'], ['readonly'], ['writeonly','allocate']]) 296 ... with it: 297 ... while not it.finished: 298 ... addop(it[0], it[1], out=it[2]) 299 ... it.iternext() 300 ... return it.operands[2] 301 302 Here is an example outer product function: 303 304 >>> def outer_it(x, y, out=None): 305 ... mulop = np.multiply 306 ... it = np.nditer([x, y, out], ['external_loop'], 307 ... [['readonly'], ['readonly'], ['writeonly', 'allocate']], 308 ... op_axes=[list(range(x.ndim)) + [-1] * y.ndim, 309 ... [-1] * x.ndim + list(range(y.ndim)), 310 ... None]) 311 ... with it: 312 ... for (a, b, c) in it: 313 ... mulop(a, b, out=c) 314 ... return it.operands[2] 315 316 >>> a = np.arange(2)+1 317 >>> b = np.arange(3)+1 318 >>> outer_it(a,b) 319 array([[1, 2, 3], 320 [2, 4, 6]]) 321 322 Here is an example function which operates like a "lambda" ufunc: 323 324 >>> def luf(lamdaexpr, *args, **kwargs): 325 ... '''luf(lambdaexpr, op1, ..., opn, out=None, order='K', casting='safe', buffersize=0)''' 326 ... nargs = len(args) 327 ... op = (kwargs.get('out',None),) + args 328 ... it = np.nditer(op, ['buffered','external_loop'], 329 ... [['writeonly','allocate','no_broadcast']] + 330 ... [['readonly','nbo','aligned']]*nargs, 331 ... order=kwargs.get('order','K'), 332 ... casting=kwargs.get('casting','safe'), 333 ... buffersize=kwargs.get('buffersize',0)) 334 ... while not it.finished: 335 ... it[0] = lamdaexpr(*it[1:]) 336 ... it.iternext() 337 ... return it.operands[0] 338 339 >>> a = np.arange(5) 340 >>> b = np.ones(5) 341 >>> luf(lambda i,j:i*i + j/2, a, b) 342 array([ 0.5, 1.5, 4.5, 9.5, 16.5]) 343 344 If operand flags ``"writeonly"`` or ``"readwrite"`` are used the 345 operands may be views into the original data with the 346 `WRITEBACKIFCOPY` flag. In this case `nditer` must be used as a 347 context manager or the `nditer.close` method must be called before 348 using the result. The temporary data will be written back to the 349 original data when the `__exit__` function is called but not before: 350 351 >>> a = np.arange(6, dtype='i4')[::-2] 352 >>> with np.nditer(a, [], 353 ... [['writeonly', 'updateifcopy']], 354 ... casting='unsafe', 355 ... op_dtypes=[np.dtype('f4')]) as i: 356 ... x = i.operands[0] 357 ... x[:] = [-1, -2, -3] 358 ... # a still unchanged here 359 >>> a, x 360 (array([-1, -2, -3], dtype=int32), array([-1., -2., -3.], dtype=float32)) 361 362 It is important to note that once the iterator is exited, dangling 363 references (like `x` in the example) may or may not share data with 364 the original data `a`. If writeback semantics were active, i.e. if 365 `x.base.flags.writebackifcopy` is `True`, then exiting the iterator 366 will sever the connection between `x` and `a`, writing to `x` will 367 no longer write to `a`. If writeback semantics are not active, then 368 `x.data` will still point at some part of `a.data`, and writing to 369 one will affect the other. 370 371 Context management and the `close` method appeared in version 1.15.0. 372 373 )r a 374 copy() 375 376 Get a copy of the iterator in its current state. 377 378 Examples 379 -------- 380 >>> x = np.arange(10) 381 >>> y = x + 1 382 >>> it = np.nditer([x, y]) 383 >>> next(it) 384 (array(0), array(1)) 385 >>> it2 = it.copy() 386 >>> next(it2) 387 (array(1), array(2)) 388 389 )�operandszl 390 operands[`Slice`] 391 392 The array(s) to be iterated over. Valid only before the iterator is closed. 393 )�debug_printzh 394 debug_print() 395 396 Print the current state of the `nditer` instance and debug info to stdout. 397 398 )�enable_external_loopz� 399 enable_external_loop() 400 401 When the "external_loop" was not used during construction, but 402 is desired, this modifies the iterator to behave as if the flag 403 was specified. 404 405 )�iternexta8 406 iternext() 407 408 Check whether iterations are left, and perform a single internal iteration 409 without returning the result. Used in the C-style pattern do-while 410 pattern. For an example, see `nditer`. 411 412 Returns 413 ------- 414 iternext : bool 415 Whether or not there are iterations left. 416 417 )�remove_axiszz 418 remove_axis(i, /) 419 420 Removes axis `i` from the iterator. Requires that the flag "multi_index" 421 be enabled. 422 423 )�remove_multi_indexz� 424 remove_multi_index() 425 426 When the "multi_index" flag was specified, this removes it, allowing 427 the internal iteration structure to be optimized further. 428 429 )�resetz@ 430 reset() 431 432 Reset the iterator to its initial state. 433 434 �nested_itersa 435 nested_iters(op, axes, flags=None, op_flags=None, op_dtypes=None, order="K", casting="safe", buffersize=0) 436 437 Create nditers for use in nested loops 438 439 Create a tuple of `nditer` objects which iterate in nested loops over 440 different axes of the op argument. The first iterator is used in the 441 outermost loop, the last in the innermost loop. Advancing one will change 442 the subsequent iterators to point at its new element. 443 444 Parameters 445 ---------- 446 op : ndarray or sequence of array_like 447 The array(s) to iterate over. 448 449 axes : list of list of int 450 Each item is used as an "op_axes" argument to an nditer 451 452 flags, op_flags, op_dtypes, order, casting, buffersize (optional) 453 See `nditer` parameters of the same name 454 455 Returns 456 ------- 457 iters : tuple of nditer 458 An nditer for each item in `axes`, outermost first 459 460 See Also 461 -------- 462 nditer 463 464 Examples 465 -------- 466 467 Basic usage. Note how y is the "flattened" version of 468 [a[:, 0, :], a[:, 1, 0], a[:, 2, :]] since we specified 469 the first iter's axes as [1] 470 471 >>> a = np.arange(12).reshape(2, 3, 2) 472 >>> i, j = np.nested_iters(a, [[1], [0, 2]], flags=["multi_index"]) 473 >>> for x in i: 474 ... print(i.multi_index) 475 ... for y in j: 476 ... print('', j.multi_index, y) 477 (0,) 478 (0, 0) 0 479 (0, 1) 1 480 (1, 0) 6 481 (1, 1) 7 482 (1,) 483 (0, 0) 2 484 (0, 1) 3 485 (1, 0) 8 486 (1, 1) 9 487 (2,) 488 (0, 0) 4 489 (0, 1) 5 490 (1, 0) 10 491 (1, 1) 11 492 493 )�closez� 494 close() 495 496 Resolve all writeback semantics in writeable operands. 497 498 .. versionadded:: 1.15.0 499 500 See Also 501 -------- 502 503 :ref:`nditer-context-manager` 504 505 � broadcasta� 506 Produce an object that mimics broadcasting. 507 508 Parameters 509 ---------- 510 in1, in2, ... : array_like 511 Input parameters. 512 513 Returns 514 ------- 515 b : broadcast object 516 Broadcast the input parameters against one another, and 517 return an object that encapsulates the result. 518 Amongst others, it has ``shape`` and ``nd`` properties, and 519 may be used as an iterator. 520 521 See Also 522 -------- 523 broadcast_arrays 524 broadcast_to 525 broadcast_shapes 526 527 Examples 528 -------- 529 530 Manually adding two vectors, using broadcasting: 531 532 >>> x = np.array([[1], [2], [3]]) 533 >>> y = np.array([4, 5, 6]) 534 >>> b = np.broadcast(x, y) 535 536 >>> out = np.empty(b.shape) 537 >>> out.flat = [u+v for (u,v) in b] 538 >>> out 539 array([[5., 6., 7.], 540 [6., 7., 8.], 541 [7., 8., 9.]]) 542 543 Compare against built-in broadcasting: 544 545 >>> x + y 546 array([[5, 6, 7], 547 [6, 7, 8], 548 [7, 8, 9]]) 549 550 )r a 551 current index in broadcasted result 552 553 Examples 554 -------- 555 >>> x = np.array([[1], [2], [3]]) 556 >>> y = np.array([4, 5, 6]) 557 >>> b = np.broadcast(x, y) 558 >>> b.index 559 0 560 >>> next(b), next(b), next(b) 561 ((1, 4), (1, 5), (1, 6)) 562 >>> b.index 563 3 564 565 )�itersa� 566 tuple of iterators along ``self``'s "components." 567 568 Returns a tuple of `numpy.flatiter` objects, one for each "component" 569 of ``self``. 570 571 See Also 572 -------- 573 numpy.flatiter 574 575 Examples 576 -------- 577 >>> x = np.array([1, 2, 3]) 578 >>> y = np.array([[4], [5], [6]]) 579 >>> b = np.broadcast(x, y) 580 >>> row, col = b.iters 581 >>> next(row), next(col) 582 (1, 4) 583 584 )�ndimz� 585 Number of dimensions of broadcasted result. Alias for `nd`. 586 587 .. versionadded:: 1.12.0 588 589 Examples 590 -------- 591 >>> x = np.array([1, 2, 3]) 592 >>> y = np.array([[4], [5], [6]]) 593 >>> b = np.broadcast(x, y) 594 >>> b.ndim 595 2 596 597 )�nda# 598 Number of dimensions of broadcasted result. For code intended for NumPy 599 1.12.0 and later the more consistent `ndim` is preferred. 600 601 Examples 602 -------- 603 >>> x = np.array([1, 2, 3]) 604 >>> y = np.array([[4], [5], [6]]) 605 >>> b = np.broadcast(x, y) 606 >>> b.nd 607 2 608 609 )�numiterz� 610 Number of iterators possessed by the broadcasted result. 611 612 Examples 613 -------- 614 >>> x = np.array([1, 2, 3]) 615 >>> y = np.array([[4], [5], [6]]) 616 >>> b = np.broadcast(x, y) 617 >>> b.numiter 618 2 619 620 )�shapez� 621 Shape of broadcasted result. 622 623 Examples 624 -------- 625 >>> x = np.array([1, 2, 3]) 626 >>> y = np.array([[4], [5], [6]]) 627 >>> b = np.broadcast(x, y) 628 >>> b.shape 629 (3, 3) 630 631 )�sizez� 632 Total size of broadcasted result. 633 634 Examples 635 -------- 636 >>> x = np.array([1, 2, 3]) 637 >>> y = np.array([[4], [5], [6]]) 638 >>> b = np.broadcast(x, y) 639 >>> b.size 640 9 641 642 )r a� 643 reset() 644 645 Reset the broadcasted result's iterator(s). 646 647 Parameters 648 ---------- 649 None 650 651 Returns 652 ------- 653 None 654 655 Examples 656 -------- 657 >>> x = np.array([1, 2, 3]) 658 >>> y = np.array([[4], [5], [6]]) 659 >>> b = np.broadcast(x, y) 660 >>> b.index 661 0 662 >>> next(b), next(b), next(b) 663 ((1, 4), (2, 4), (3, 4)) 664 >>> b.index 665 3 666 >>> b.reset() 667 >>> b.index 668 0 669 670 znumpy.core.multiarray�arraya� 671 array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, 672 like=None) 673 674 Create an array. 675 676 Parameters 677 ---------- 678 object : array_like 679 An array, any object exposing the array interface, an object whose 680 __array__ method returns an array, or any (nested) sequence. 681 If object is a scalar, a 0-dimensional array containing object is 682 returned. 683 dtype : data-type, optional 684 The desired data-type for the array. If not given, then the type will 685 be determined as the minimum type required to hold the objects in the 686 sequence. 687 copy : bool, optional 688 If true (default), then the object is copied. Otherwise, a copy will 689 only be made if __array__ returns a copy, if obj is a nested sequence, 690 or if a copy is needed to satisfy any of the other requirements 691 (`dtype`, `order`, etc.). 692 order : {'K', 'A', 'C', 'F'}, optional 693 Specify the memory layout of the array. If object is not an array, the 694 newly created array will be in C order (row major) unless 'F' is 695 specified, in which case it will be in Fortran order (column major). 696 If object is an array the following holds. 697 698 ===== ========= =================================================== 699 order no copy copy=True 700 ===== ========= =================================================== 701 'K' unchanged F & C order preserved, otherwise most similar order 702 'A' unchanged F order if input is F and not C, otherwise C order 703 'C' C order C order 704 'F' F order F order 705 ===== ========= =================================================== 706 707 When ``copy=False`` and a copy is made for other reasons, the result is 708 the same as if ``copy=True``, with some exceptions for 'A', see the 709 Notes section. The default order is 'K'. 710 subok : bool, optional 711 If True, then sub-classes will be passed-through, otherwise 712 the returned array will be forced to be a base-class array (default). 713 ndmin : int, optional 714 Specifies the minimum number of dimensions that the resulting 715 array should have. Ones will be prepended to the shape as 716 needed to meet this requirement. 717 ${ARRAY_FUNCTION_LIKE} 718 719 .. versionadded:: 1.20.0 720 721 Returns 722 ------- 723 out : ndarray 724 An array object satisfying the specified requirements. 725 726 See Also 727 -------- 728 empty_like : Return an empty array with shape and type of input. 729 ones_like : Return an array of ones with shape and type of input. 730 zeros_like : Return an array of zeros with shape and type of input. 731 full_like : Return a new array with shape of input filled with value. 732 empty : Return a new uninitialized array. 733 ones : Return a new array setting values to one. 734 zeros : Return a new array setting values to zero. 735 full : Return a new array of given shape filled with value. 736 737 738 Notes 739 ----- 740 When order is 'A' and `object` is an array in neither 'C' nor 'F' order, 741 and a copy is forced by a change in dtype, then the order of the result is 742 not necessarily 'C' as expected. This is likely a bug. 743 744 Examples 745 -------- 746 >>> np.array([1, 2, 3]) 747 array([1, 2, 3]) 748 749 Upcasting: 750 751 >>> np.array([1, 2, 3.0]) 752 array([ 1., 2., 3.]) 753 754 More than one dimension: 755 756 >>> np.array([[1, 2], [3, 4]]) 757 array([[1, 2], 758 [3, 4]]) 759 760 Minimum dimensions 2: 761 762 >>> np.array([1, 2, 3], ndmin=2) 763 array([[1, 2, 3]]) 764 765 Type provided: 766 767 >>> np.array([1, 2, 3], dtype=complex) 768 array([ 1.+0.j, 2.+0.j, 3.+0.j]) 769 770 Data-type consisting of more than one element: 771 772 >>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')]) 773 >>> x['a'] 774 array([1, 3]) 775 776 Creating an array from sub-classes: 777 778 >>> np.array(np.mat('1 2; 3 4')) 779 array([[1, 2], 780 [3, 4]]) 781 782 >>> np.array(np.mat('1 2; 3 4'), subok=True) 783 matrix([[1, 2], 784 [3, 4]]) 785 786 z${ARRAY_FUNCTION_LIKE}�asarraya8 787 asarray(a, dtype=None, order=None, *, like=None) 788 789 Convert the input to an array. 790 791 Parameters 792 ---------- 793 a : array_like 794 Input data, in any form that can be converted to an array. This 795 includes lists, lists of tuples, tuples, tuples of tuples, tuples 796 of lists and ndarrays. 797 dtype : data-type, optional 798 By default, the data-type is inferred from the input data. 799 order : {'C', 'F', 'A', 'K'}, optional 800 Memory layout. 'A' and 'K' depend on the order of input array a. 801 'C' row-major (C-style), 802 'F' column-major (Fortran-style) memory representation. 803 'A' (any) means 'F' if `a` is Fortran contiguous, 'C' otherwise 804 'K' (keep) preserve input order 805 Defaults to 'K'. 806 ${ARRAY_FUNCTION_LIKE} 807 808 .. versionadded:: 1.20.0 809 810 Returns 811 ------- 812 out : ndarray 813 Array interpretation of `a`. No copy is performed if the input 814 is already an ndarray with matching dtype and order. If `a` is a 815 subclass of ndarray, a base class ndarray is returned. 816 817 See Also 818 -------- 819 asanyarray : Similar function which passes through subclasses. 820 ascontiguousarray : Convert input to a contiguous array. 821 asfarray : Convert input to a floating point ndarray. 822 asfortranarray : Convert input to an ndarray with column-major 823 memory order. 824 asarray_chkfinite : Similar function which checks input for NaNs and Infs. 825 fromiter : Create an array from an iterator. 826 fromfunction : Construct an array by executing a function on grid 827 positions. 828 829 Examples 830 -------- 831 Convert a list into an array: 832 833 >>> a = [1, 2] 834 >>> np.asarray(a) 835 array([1, 2]) 836 837 Existing arrays are not copied: 838 839 >>> a = np.array([1, 2]) 840 >>> np.asarray(a) is a 841 True 842 843 If `dtype` is set, array is copied only if dtype does not match: 844 845 >>> a = np.array([1, 2], dtype=np.float32) 846 >>> np.asarray(a, dtype=np.float32) is a 847 True 848 >>> np.asarray(a, dtype=np.float64) is a 849 False 850 851 Contrary to `asanyarray`, ndarray subclasses are not passed through: 852 853 >>> issubclass(np.recarray, np.ndarray) 854 True 855 >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray) 856 >>> np.asarray(a) is a 857 False 858 >>> np.asanyarray(a) is a 859 True 860 861 � 862 asanyarraya� 863 asanyarray(a, dtype=None, order=None, *, like=None) 864 865 Convert the input to an ndarray, but pass ndarray subclasses through. 866 867 Parameters 868 ---------- 869 a : array_like 870 Input data, in any form that can be converted to an array. This 871 includes scalars, lists, lists of tuples, tuples, tuples of tuples, 872 tuples of lists, and ndarrays. 873 dtype : data-type, optional 874 By default, the data-type is inferred from the input data. 875 order : {'C', 'F', 'A', 'K'}, optional 876 Memory layout. 'A' and 'K' depend on the order of input array a. 877 'C' row-major (C-style), 878 'F' column-major (Fortran-style) memory representation. 879 'A' (any) means 'F' if `a` is Fortran contiguous, 'C' otherwise 880 'K' (keep) preserve input order 881 Defaults to 'C'. 882 ${ARRAY_FUNCTION_LIKE} 883 884 .. versionadded:: 1.20.0 885 886 Returns 887 ------- 888 out : ndarray or an ndarray subclass 889 Array interpretation of `a`. If `a` is an ndarray or a subclass 890 of ndarray, it is returned as-is and no copy is performed. 891 892 See Also 893 -------- 894 asarray : Similar function which always returns ndarrays. 895 ascontiguousarray : Convert input to a contiguous array. 896 asfarray : Convert input to a floating point ndarray. 897 asfortranarray : Convert input to an ndarray with column-major 898 memory order. 899 asarray_chkfinite : Similar function which checks input for NaNs and 900 Infs. 901 fromiter : Create an array from an iterator. 902 fromfunction : Construct an array by executing a function on grid 903 positions. 904 905 Examples 906 -------- 907 Convert a list into an array: 908 909 >>> a = [1, 2] 910 >>> np.asanyarray(a) 911 array([1, 2]) 912 913 Instances of `ndarray` subclasses are passed through as-is: 914 915 >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray) 916 >>> np.asanyarray(a) is a 917 True 918 919 �ascontiguousarraya� 920 ascontiguousarray(a, dtype=None, *, like=None) 921 922 Return a contiguous array (ndim >= 1) in memory (C order). 923 924 Parameters 925 ---------- 926 a : array_like 927 Input array. 928 dtype : str or dtype object, optional 929 Data-type of returned array. 930 ${ARRAY_FUNCTION_LIKE} 931 932 .. versionadded:: 1.20.0 933 934 Returns 935 ------- 936 out : ndarray 937 Contiguous array of same shape and content as `a`, with type `dtype` 938 if specified. 939 940 See Also 941 -------- 942 asfortranarray : Convert input to an ndarray with column-major 943 memory order. 944 require : Return an ndarray that satisfies requirements. 945 ndarray.flags : Information about the memory layout of the array. 946 947 Examples 948 -------- 949 Starting with a Fortran-contiguous array: 950 951 >>> x = np.ones((2, 3), order='F') 952 >>> x.flags['F_CONTIGUOUS'] 953 True 954 955 Calling ``ascontiguousarray`` makes a C-contiguous copy: 956 957 >>> y = np.ascontiguousarray(x) 958 >>> y.flags['C_CONTIGUOUS'] 959 True 960 >>> np.may_share_memory(x, y) 961 False 962 963 Now, starting with a C-contiguous array: 964 965 >>> x = np.ones((2, 3), order='C') 966 >>> x.flags['C_CONTIGUOUS'] 967 True 968 969 Then, calling ``ascontiguousarray`` returns the same object: 970 971 >>> y = np.ascontiguousarray(x) 972 >>> x is y 973 True 974 975 Note: This function returns an array with at least one-dimension (1-d) 976 so it will not preserve 0-d arrays. 977 978 �asfortranarraya� 979 asfortranarray(a, dtype=None, *, like=None) 980 981 Return an array (ndim >= 1) laid out in Fortran order in memory. 982 983 Parameters 984 ---------- 985 a : array_like 986 Input array. 987 dtype : str or dtype object, optional 988 By default, the data-type is inferred from the input data. 989 ${ARRAY_FUNCTION_LIKE} 990 991 .. versionadded:: 1.20.0 992 993 Returns 994 ------- 995 out : ndarray 996 The input `a` in Fortran, or column-major, order. 997 998 See Also 999 -------- 1000 ascontiguousarray : Convert input to a contiguous (C order) array. 1001 asanyarray : Convert input to an ndarray with either row or 1002 column-major memory order. 1003 require : Return an ndarray that satisfies requirements. 1004 ndarray.flags : Information about the memory layout of the array. 1005 1006 Examples 1007 -------- 1008 Starting with a C-contiguous array: 1009 1010 >>> x = np.ones((2, 3), order='C') 1011 >>> x.flags['C_CONTIGUOUS'] 1012 True 1013 1014 Calling ``asfortranarray`` makes a Fortran-contiguous copy: 1015 1016 >>> y = np.asfortranarray(x) 1017 >>> y.flags['F_CONTIGUOUS'] 1018 True 1019 >>> np.may_share_memory(x, y) 1020 False 1021 1022 Now, starting with a Fortran-contiguous array: 1023 1024 >>> x = np.ones((2, 3), order='F') 1025 >>> x.flags['F_CONTIGUOUS'] 1026 True 1027 1028 Then, calling ``asfortranarray`` returns the same object: 1029 1030 >>> y = np.asfortranarray(x) 1031 >>> x is y 1032 True 1033 1034 Note: This function returns an array with at least one-dimension (1-d) 1035 so it will not preserve 0-d arrays. 1036 1037 �emptya� 1038 empty(shape, dtype=float, order='C', *, like=None) 1039 1040 Return a new array of given shape and type, without initializing entries. 1041 1042 Parameters 1043 ---------- 1044 shape : int or tuple of int 1045 Shape of the empty array, e.g., ``(2, 3)`` or ``2``. 1046 dtype : data-type, optional 1047 Desired output data-type for the array, e.g, `numpy.int8`. Default is 1048 `numpy.float64`. 1049 order : {'C', 'F'}, optional, default: 'C' 1050 Whether to store multi-dimensional data in row-major 1051 (C-style) or column-major (Fortran-style) order in 1052 memory. 1053 ${ARRAY_FUNCTION_LIKE} 1054 1055 .. versionadded:: 1.20.0 1056 1057 Returns 1058 ------- 1059 out : ndarray 1060 Array of uninitialized (arbitrary) data of the given shape, dtype, and 1061 order. Object arrays will be initialized to None. 1062 1063 See Also 1064 -------- 1065 empty_like : Return an empty array with shape and type of input. 1066 ones : Return a new array setting values to one. 1067 zeros : Return a new array setting values to zero. 1068 full : Return a new array of given shape filled with value. 1069 1070 1071 Notes 1072 ----- 1073 `empty`, unlike `zeros`, does not set the array values to zero, 1074 and may therefore be marginally faster. On the other hand, it requires 1075 the user to manually set all the values in the array, and should be 1076 used with caution. 1077 1078 Examples 1079 -------- 1080 >>> np.empty([2, 2]) 1081 array([[ -9.74499359e+001, 6.69583040e-309], 1082 [ 2.13182611e-314, 3.06959433e-309]]) #uninitialized 1083 1084 >>> np.empty([2, 2], dtype=int) 1085 array([[-1073741821, -1067949133], 1086 [ 496041986, 19249760]]) #uninitialized 1087 1088 �scalara� 1089 scalar(dtype, obj) 1090 1091 Return a new scalar array of the given type initialized with obj. 1092 1093 This function is meant mainly for pickle support. `dtype` must be a 1094 valid data-type descriptor. If `dtype` corresponds to an object 1095 descriptor, then `obj` can be any object, otherwise `obj` must be a 1096 string. If `obj` is not given, it will be interpreted as None for object 1097 type and as zeros for all other types. 1098 1099 �zerosa� 1100 zeros(shape, dtype=float, order='C', *, like=None) 1101 1102 Return a new array of given shape and type, filled with zeros. 1103 1104 Parameters 1105 ---------- 1106 shape : int or tuple of ints 1107 Shape of the new array, e.g., ``(2, 3)`` or ``2``. 1108 dtype : data-type, optional 1109 The desired data-type for the array, e.g., `numpy.int8`. Default is 1110 `numpy.float64`. 1111 order : {'C', 'F'}, optional, default: 'C' 1112 Whether to store multi-dimensional data in row-major 1113 (C-style) or column-major (Fortran-style) order in 1114 memory. 1115 ${ARRAY_FUNCTION_LIKE} 1116 1117 .. versionadded:: 1.20.0 1118 1119 Returns 1120 ------- 1121 out : ndarray 1122 Array of zeros with the given shape, dtype, and order. 1123 1124 See Also 1125 -------- 1126 zeros_like : Return an array of zeros with shape and type of input. 1127 empty : Return a new uninitialized array. 1128 ones : Return a new array setting values to one. 1129 full : Return a new array of given shape filled with value. 1130 1131 Examples 1132 -------- 1133 >>> np.zeros(5) 1134 array([ 0., 0., 0., 0., 0.]) 1135 1136 >>> np.zeros((5,), dtype=int) 1137 array([0, 0, 0, 0, 0]) 1138 1139 >>> np.zeros((2, 1)) 1140 array([[ 0.], 1141 [ 0.]]) 1142 1143 >>> s = (2,2) 1144 >>> np.zeros(s) 1145 array([[ 0., 0.], 1146 [ 0., 0.]]) 1147 1148 >>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype 1149 array([(0, 0), (0, 0)], 1150 dtype=[('x', '<i4'), ('y', '<i4')]) 1151 1152 �set_typeDictzuset_typeDict(dict) 1153 1154 Set the internal dictionary that can look up an array type using a 1155 registered code. 1156 1157 � 1158 fromstringag 1159 fromstring(string, dtype=float, count=-1, *, sep, like=None) 1160 1161 A new 1-D array initialized from text data in a string. 1162 1163 Parameters 1164 ---------- 1165 string : str 1166 A string containing the data. 1167 dtype : data-type, optional 1168 The data type of the array; default: float. For binary input data, 1169 the data must be in exactly this format. Most builtin numeric types are 1170 supported and extension types may be supported. 1171 1172 .. versionadded:: 1.18.0 1173 Complex dtypes. 1174 1175 count : int, optional 1176 Read this number of `dtype` elements from the data. If this is 1177 negative (the default), the count will be determined from the 1178 length of the data. 1179 sep : str, optional 1180 The string separating numbers in the data; extra whitespace between 1181 elements is also ignored. 1182 1183 .. deprecated:: 1.14 1184 Passing ``sep=''``, the default, is deprecated since it will 1185 trigger the deprecated binary mode of this function. This mode 1186 interprets `string` as binary bytes, rather than ASCII text with 1187 decimal numbers, an operation which is better spelt 1188 ``frombuffer(string, dtype, count)``. If `string` contains unicode 1189 text, the binary mode of `fromstring` will first encode it into 1190 bytes using utf-8, which will not produce sane results. 1191 1192 ${ARRAY_FUNCTION_LIKE} 1193 1194 .. versionadded:: 1.20.0 1195 1196 Returns 1197 ------- 1198 arr : ndarray 1199 The constructed array. 1200 1201 Raises 1202 ------ 1203 ValueError 1204 If the string is not the correct size to satisfy the requested 1205 `dtype` and `count`. 1206 1207 See Also 1208 -------- 1209 frombuffer, fromfile, fromiter 1210 1211 Examples 1212 -------- 1213 >>> np.fromstring('1 2', dtype=int, sep=' ') 1214 array([1, 2]) 1215 >>> np.fromstring('1, 2', dtype=int, sep=',') 1216 array([1, 2]) 1217 1218 �compare_chararraysap 1219 compare_chararrays(a1, a2, cmp, rstrip) 1220 1221 Performs element-wise comparison of two string arrays using the 1222 comparison operator specified by `cmp_op`. 1223 1224 Parameters 1225 ---------- 1226 a1, a2 : array_like 1227 Arrays to be compared. 1228 cmp : {"<", "<=", "==", ">=", ">", "!="} 1229 Type of comparison. 1230 rstrip : Boolean 1231 If True, the spaces at the end of Strings are removed before the comparison. 1232 1233 Returns 1234 ------- 1235 out : ndarray 1236 The output array of type Boolean with the same shape as a and b. 1237 1238 Raises 1239 ------ 1240 ValueError 1241 If `cmp_op` is not valid. 1242 TypeError 1243 If at least one of `a` or `b` is a non-string array 1244 1245 Examples 1246 -------- 1247 >>> a = np.array(["a", "b", "cde"]) 1248 >>> b = np.array(["a", "a", "dec"]) 1249 >>> np.compare_chararrays(a, b, ">", True) 1250 array([False, True, False]) 1251 1252 �fromitera9 1253 fromiter(iter, dtype, count=-1, *, like=None) 1254 1255 Create a new 1-dimensional array from an iterable object. 1256 1257 Parameters 1258 ---------- 1259 iter : iterable object 1260 An iterable object providing data for the array. 1261 dtype : data-type 1262 The data-type of the returned array. 1263 1264 .. versionchanged:: 1.23 1265 Object and subarray dtypes are now supported (note that the final 1266 result is not 1-D for a subarray dtype). 1267 1268 count : int, optional 1269 The number of items to read from *iterable*. The default is -1, 1270 which means all data is read. 1271 ${ARRAY_FUNCTION_LIKE} 1272 1273 .. versionadded:: 1.20.0 1274 1275 Returns 1276 ------- 1277 out : ndarray 1278 The output array. 1279 1280 Notes 1281 ----- 1282 Specify `count` to improve performance. It allows ``fromiter`` to 1283 pre-allocate the output array, instead of resizing it on demand. 1284 1285 Examples 1286 -------- 1287 >>> iterable = (x*x for x in range(5)) 1288 >>> np.fromiter(iterable, float) 1289 array([ 0., 1., 4., 9., 16.]) 1290 1291 A carefully constructed subarray dtype will lead to higher dimensional 1292 results: 1293 1294 >>> iterable = ((x+1, x+2) for x in range(5)) 1295 >>> np.fromiter(iterable, dtype=np.dtype((int, 2))) 1296 array([[1, 2], 1297 [2, 3], 1298 [3, 4], 1299 [4, 5], 1300 [5, 6]]) 1301 1302 1303 �fromfilea/ 1304 fromfile(file, dtype=float, count=-1, sep='', offset=0, *, like=None) 1305 1306 Construct an array from data in a text or binary file. 1307 1308 A highly efficient way of reading binary data with a known data-type, 1309 as well as parsing simply formatted text files. Data written using the 1310 `tofile` method can be read using this function. 1311 1312 Parameters 1313 ---------- 1314 file : file or str or Path 1315 Open file object or filename. 1316 1317 .. versionchanged:: 1.17.0 1318 `pathlib.Path` objects are now accepted. 1319 1320 dtype : data-type 1321 Data type of the returned array. 1322 For binary files, it is used to determine the size and byte-order 1323 of the items in the file. 1324 Most builtin numeric types are supported and extension types may be supported. 1325 1326 .. versionadded:: 1.18.0 1327 Complex dtypes. 1328 1329 count : int 1330 Number of items to read. ``-1`` means all items (i.e., the complete 1331 file). 1332 sep : str 1333 Separator between items if file is a text file. 1334 Empty ("") separator means the file should be treated as binary. 1335 Spaces (" ") in the separator match zero or more whitespace characters. 1336 A separator consisting only of spaces must match at least one 1337 whitespace. 1338 offset : int 1339 The offset (in bytes) from the file's current position. Defaults to 0. 1340 Only permitted for binary files. 1341 1342 .. versionadded:: 1.17.0 1343 ${ARRAY_FUNCTION_LIKE} 1344 1345 .. versionadded:: 1.20.0 1346 1347 See also 1348 -------- 1349 load, save 1350 ndarray.tofile 1351 loadtxt : More flexible way of loading data from a text file. 1352 1353 Notes 1354 ----- 1355 Do not rely on the combination of `tofile` and `fromfile` for 1356 data storage, as the binary files generated are not platform 1357 independent. In particular, no byte-order or data-type information is 1358 saved. Data can be stored in the platform independent ``.npy`` format 1359 using `save` and `load` instead. 1360 1361 Examples 1362 -------- 1363 Construct an ndarray: 1364 1365 >>> dt = np.dtype([('time', [('min', np.int64), ('sec', np.int64)]), 1366 ... ('temp', float)]) 1367 >>> x = np.zeros((1,), dtype=dt) 1368 >>> x['time']['min'] = 10; x['temp'] = 98.25 1369 >>> x 1370 array([((10, 0), 98.25)], 1371 dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')]) 1372 1373 Save the raw data to disk: 1374 1375 >>> import tempfile 1376 >>> fname = tempfile.mkstemp()[1] 1377 >>> x.tofile(fname) 1378 1379 Read the raw data from disk: 1380 1381 >>> np.fromfile(fname, dtype=dt) 1382 array([((10, 0), 98.25)], 1383 dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')]) 1384 1385 The recommended way to store and load data: 1386 1387 >>> np.save(fname, x) 1388 >>> np.load(fname + '.npy') 1389 array([((10, 0), 98.25)], 1390 dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')]) 1391 1392 � 1393 frombuffera� 1394 frombuffer(buffer, dtype=float, count=-1, offset=0, *, like=None) 1395 1396 Interpret a buffer as a 1-dimensional array. 1397 1398 Parameters 1399 ---------- 1400 buffer : buffer_like 1401 An object that exposes the buffer interface. 1402 dtype : data-type, optional 1403 Data-type of the returned array; default: float. 1404 count : int, optional 1405 Number of items to read. ``-1`` means all data in the buffer. 1406 offset : int, optional 1407 Start reading the buffer from this offset (in bytes); default: 0. 1408 ${ARRAY_FUNCTION_LIKE} 1409 1410 .. versionadded:: 1.20.0 1411 1412 Returns 1413 ------- 1414 out : ndarray 1415 1416 See also 1417 -------- 1418 ndarray.tobytes 1419 Inverse of this operation, construct Python bytes from the raw data 1420 bytes in the array. 1421 1422 Notes 1423 ----- 1424 If the buffer has data that is not in machine byte-order, this should 1425 be specified as part of the data-type, e.g.:: 1426 1427 >>> dt = np.dtype(int) 1428 >>> dt = dt.newbyteorder('>') 1429 >>> np.frombuffer(buf, dtype=dt) # doctest: +SKIP 1430 1431 The data of the resulting array will not be byteswapped, but will be 1432 interpreted correctly. 1433 1434 This function creates a view into the original object. This should be safe 1435 in general, but it may make sense to copy the result when the original 1436 object is mutable or untrusted. 1437 1438 Examples 1439 -------- 1440 >>> s = b'hello world' 1441 >>> np.frombuffer(s, dtype='S1', count=5, offset=6) 1442 array([b'w', b'o', b'r', b'l', b'd'], dtype='|S1') 1443 1444 >>> np.frombuffer(b'\x01\x02', dtype=np.uint8) 1445 array([1, 2], dtype=uint8) 1446 >>> np.frombuffer(b'\x01\x02\x03\x04\x05', dtype=np.uint8, count=3) 1447 array([1, 2, 3], dtype=uint8) 1448 1449 �from_dlpackaq 1450 from_dlpack(x, /) 1451 1452 Create a NumPy array from an object implementing the ``__dlpack__`` 1453 protocol. Generally, the returned NumPy array is a read-only view 1454 of the input object. See [1]_ and [2]_ for more details. 1455 1456 Parameters 1457 ---------- 1458 x : object 1459 A Python object that implements the ``__dlpack__`` and 1460 ``__dlpack_device__`` methods. 1461 1462 Returns 1463 ------- 1464 out : ndarray 1465 1466 References 1467 ---------- 1468 .. [1] Array API documentation, 1469 https://data-apis.org/array-api/latest/design_topics/data_interchange.html#syntax-for-data-interchange-with-dlpack 1470 1471 .. [2] Python specification for DLPack, 1472 https://dmlc.github.io/dlpack/latest/python_spec.html 1473 1474 Examples 1475 -------- 1476 >>> import torch 1477 >>> x = torch.arange(10) 1478 >>> # create a view of the torch tensor "x" in NumPy 1479 >>> y = np.from_dlpack(x) 1480 �fastCopyAndTransposez� 1481 fastCopyAndTranspose(a) 1482 1483 .. deprecated:: 1.24 1484 1485 fastCopyAndTranspose is deprecated and will be removed. Use the copy and 1486 transpose methods instead, e.g. ``arr.T.copy()`` 1487 � correlatezcross_correlate(a,v, mode=0)�arangea� 1488 arange([start,] stop[, step,], dtype=None, *, like=None) 1489 1490 Return evenly spaced values within a given interval. 1491 1492 ``arange`` can be called with a varying number of positional arguments: 1493 1494 * ``arange(stop)``: Values are generated within the half-open interval 1495 ``[0, stop)`` (in other words, the interval including `start` but 1496 excluding `stop`). 1497 * ``arange(start, stop)``: Values are generated within the half-open 1498 interval ``[start, stop)``. 1499 * ``arange(start, stop, step)`` Values are generated within the half-open 1500 interval ``[start, stop)``, with spacing between values given by 1501 ``step``. 1502 1503 For integer arguments the function is roughly equivalent to the Python 1504 built-in :py:class:`range`, but returns an ndarray rather than a ``range`` 1505 instance. 1506 1507 When using a non-integer step, such as 0.1, it is often better to use 1508 `numpy.linspace`. 1509 1510 See the Warning sections below for more information. 1511 1512 Parameters 1513 ---------- 1514 start : integer or real, optional 1515 Start of interval. The interval includes this value. The default 1516 start value is 0. 1517 stop : integer or real 1518 End of interval. The interval does not include this value, except 1519 in some cases where `step` is not an integer and floating point 1520 round-off affects the length of `out`. 1521 step : integer or real, optional 1522 Spacing between values. For any output `out`, this is the distance 1523 between two adjacent values, ``out[i+1] - out[i]``. The default 1524 step size is 1. If `step` is specified as a position argument, 1525 `start` must also be given. 1526 dtype : dtype, optional 1527 The type of the output array. If `dtype` is not given, infer the data 1528 type from the other input arguments. 1529 ${ARRAY_FUNCTION_LIKE} 1530 1531 .. versionadded:: 1.20.0 1532 1533 Returns 1534 ------- 1535 arange : ndarray 1536 Array of evenly spaced values. 1537 1538 For floating point arguments, the length of the result is 1539 ``ceil((stop - start)/step)``. Because of floating point overflow, 1540 this rule may result in the last element of `out` being greater 1541 than `stop`. 1542 1543 Warnings 1544 -------- 1545 The length of the output might not be numerically stable. 1546 1547 Another stability issue is due to the internal implementation of 1548 `numpy.arange`. 1549 The actual step value used to populate the array is 1550 ``dtype(start + step) - dtype(start)`` and not `step`. Precision loss 1551 can occur here, due to casting or due to using floating points when 1552 `start` is much larger than `step`. This can lead to unexpected 1553 behaviour. For example:: 1554 1555 >>> np.arange(0, 5, 0.5, dtype=int) 1556 array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) 1557 >>> np.arange(-3, 3, 0.5, dtype=int) 1558 array([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8]) 1559 1560 In such cases, the use of `numpy.linspace` should be preferred. 1561 1562 The built-in :py:class:`range` generates :std:doc:`Python built-in integers 1563 that have arbitrary size <python:c-api/long>`, while `numpy.arange` 1564 produces `numpy.int32` or `numpy.int64` numbers. This may result in 1565 incorrect results for large integer values:: 1566 1567 >>> power = 40 1568 >>> modulo = 10000 1569 >>> x1 = [(n ** power) % modulo for n in range(8)] 1570 >>> x2 = [(n ** power) % modulo for n in np.arange(8)] 1571 >>> print(x1) 1572 [0, 1, 7776, 8801, 6176, 625, 6576, 4001] # correct 1573 >>> print(x2) 1574 [0, 1, 7776, 7185, 0, 5969, 4816, 3361] # incorrect 1575 1576 See Also 1577 -------- 1578 numpy.linspace : Evenly spaced numbers with careful handling of endpoints. 1579 numpy.ogrid: Arrays of evenly spaced numbers in N-dimensions. 1580 numpy.mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions. 1581 :ref:`how-to-partition` 1582 1583 Examples 1584 -------- 1585 >>> np.arange(3) 1586 array([0, 1, 2]) 1587 >>> np.arange(3.0) 1588 array([ 0., 1., 2.]) 1589 >>> np.arange(3,7) 1590 array([3, 4, 5, 6]) 1591 >>> np.arange(3,7,2) 1592 array([3, 5]) 1593 1594 �_get_ndarray_c_versionzq_get_ndarray_c_version() 1595 1596 Return the compile time NPY_VERSION (formerly called NDARRAY_VERSION) number. 1597 1598 �_reconstructzY_reconstruct(subtype, shape, dtype) 1599 1600 Construct an empty array. Used by Pickles. 1601 1602 �set_string_functionzx 1603 set_string_function(f, repr=1) 1604 1605 Internal method to set a function to be used when pretty printing arrays. 1606 1607 �set_numeric_opsa" 1608 set_numeric_ops(op1=func1, op2=func2, ...) 1609 1610 Set numerical operators for array objects. 1611 1612 .. deprecated:: 1.16 1613 1614 For the general case, use :c:func:`PyUFunc_ReplaceLoopBySignature`. 1615 For ndarray subclasses, define the ``__array_ufunc__`` method and 1616 override the relevant ufunc. 1617 1618 Parameters 1619 ---------- 1620 op1, op2, ... : callable 1621 Each ``op = func`` pair describes an operator to be replaced. 1622 For example, ``add = lambda x, y: np.add(x, y) % 5`` would replace 1623 addition by modulus 5 addition. 1624 1625 Returns 1626 ------- 1627 saved_ops : list of callables 1628 A list of all operators, stored before making replacements. 1629 1630 Notes 1631 ----- 1632 .. warning:: 1633 Use with care! Incorrect usage may lead to memory errors. 1634 1635 A function replacing an operator cannot make use of that operator. 1636 For example, when replacing add, you may not use ``+``. Instead, 1637 directly call ufuncs. 1638 1639 Examples 1640 -------- 1641 >>> def add_mod5(x, y): 1642 ... return np.add(x, y) % 5 1643 ... 1644 >>> old_funcs = np.set_numeric_ops(add=add_mod5) 1645 1646 >>> x = np.arange(12).reshape((3, 4)) 1647 >>> x + x 1648 array([[0, 2, 4, 1], 1649 [3, 0, 2, 4], 1650 [1, 3, 0, 2]]) 1651 1652 >>> ignore = np.set_numeric_ops(**old_funcs) # restore operators 1653 1654 � promote_typesa� 1655 promote_types(type1, type2) 1656 1657 Returns the data type with the smallest size and smallest scalar 1658 kind to which both ``type1`` and ``type2`` may be safely cast. 1659 The returned data type is always considered "canonical", this mainly 1660 means that the promoted dtype will always be in native byte order. 1661 1662 This function is symmetric, but rarely associative. 1663 1664 Parameters 1665 ---------- 1666 type1 : dtype or dtype specifier 1667 First data type. 1668 type2 : dtype or dtype specifier 1669 Second data type. 1670 1671 Returns 1672 ------- 1673 out : dtype 1674 The promoted data type. 1675 1676 Notes 1677 ----- 1678 Please see `numpy.result_type` for additional information about promotion. 1679 1680 .. versionadded:: 1.6.0 1681 1682 Starting in NumPy 1.9, promote_types function now returns a valid string 1683 length when given an integer or float dtype as one argument and a string 1684 dtype as another argument. Previously it always returned the input string 1685 dtype, even if it wasn't long enough to store the max integer/float value 1686 converted to a string. 1687 1688 .. versionchanged:: 1.23.0 1689 1690 NumPy now supports promotion for more structured dtypes. It will now 1691 remove unnecessary padding from a structure dtype and promote included 1692 fields individually. 1693 1694 See Also 1695 -------- 1696 result_type, dtype, can_cast 1697 1698 Examples 1699 -------- 1700 >>> np.promote_types('f4', 'f8') 1701 dtype('float64') 1702 1703 >>> np.promote_types('i8', 'f4') 1704 dtype('float64') 1705 1706 >>> np.promote_types('>i8', '<c8') 1707 dtype('complex128') 1708 1709 >>> np.promote_types('i4', 'S8') 1710 dtype('S11') 1711 1712 An example of a non-associative case: 1713 1714 >>> p = np.promote_types 1715 >>> p('S', p('i1', 'u1')) 1716 dtype('S6') 1717 >>> p(p('S', 'i1'), 'u1') 1718 dtype('S4') 1719 1720 �c_einsuma�, 1721 c_einsum(subscripts, *operands, out=None, dtype=None, order='K', 1722 casting='safe') 1723 1724 *This documentation shadows that of the native python implementation of the `einsum` function, 1725 except all references and examples related to the `optimize` argument (v 0.12.0) have been removed.* 1726 1727 Evaluates the Einstein summation convention on the operands. 1728 1729 Using the Einstein summation convention, many common multi-dimensional, 1730 linear algebraic array operations can be represented in a simple fashion. 1731 In *implicit* mode `einsum` computes these values. 1732 1733 In *explicit* mode, `einsum` provides further flexibility to compute 1734 other array operations that might not be considered classical Einstein 1735 summation operations, by disabling, or forcing summation over specified 1736 subscript labels. 1737 1738 See the notes and examples for clarification. 1739 1740 Parameters 1741 ---------- 1742 subscripts : str 1743 Specifies the subscripts for summation as comma separated list of 1744 subscript labels. An implicit (classical Einstein summation) 1745 calculation is performed unless the explicit indicator '->' is 1746 included as well as subscript labels of the precise output form. 1747 operands : list of array_like 1748 These are the arrays for the operation. 1749 out : ndarray, optional 1750 If provided, the calculation is done into this array. 1751 dtype : {data-type, None}, optional 1752 If provided, forces the calculation to use the data type specified. 1753 Note that you may have to also give a more liberal `casting` 1754 parameter to allow the conversions. Default is None. 1755 order : {'C', 'F', 'A', 'K'}, optional 1756 Controls the memory layout of the output. 'C' means it should 1757 be C contiguous. 'F' means it should be Fortran contiguous, 1758 'A' means it should be 'F' if the inputs are all 'F', 'C' otherwise. 1759 'K' means it should be as close to the layout of the inputs as 1760 is possible, including arbitrarily permuted axes. 1761 Default is 'K'. 1762 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional 1763 Controls what kind of data casting may occur. Setting this to 1764 'unsafe' is not recommended, as it can adversely affect accumulations. 1765 1766 * 'no' means the data types should not be cast at all. 1767 * 'equiv' means only byte-order changes are allowed. 1768 * 'safe' means only casts which can preserve values are allowed. 1769 * 'same_kind' means only safe casts or casts within a kind, 1770 like float64 to float32, are allowed. 1771 * 'unsafe' means any data conversions may be done. 1772 1773 Default is 'safe'. 1774 optimize : {False, True, 'greedy', 'optimal'}, optional 1775 Controls if intermediate optimization should occur. No optimization 1776 will occur if False and True will default to the 'greedy' algorithm. 1777 Also accepts an explicit contraction list from the ``np.einsum_path`` 1778 function. See ``np.einsum_path`` for more details. Defaults to False. 1779 1780 Returns 1781 ------- 1782 output : ndarray 1783 The calculation based on the Einstein summation convention. 1784 1785 See Also 1786 -------- 1787 einsum_path, dot, inner, outer, tensordot, linalg.multi_dot 1788 1789 Notes 1790 ----- 1791 .. versionadded:: 1.6.0 1792 1793 The Einstein summation convention can be used to compute 1794 many multi-dimensional, linear algebraic array operations. `einsum` 1795 provides a succinct way of representing these. 1796 1797 A non-exhaustive list of these operations, 1798 which can be computed by `einsum`, is shown below along with examples: 1799 1800 * Trace of an array, :py:func:`numpy.trace`. 1801 * Return a diagonal, :py:func:`numpy.diag`. 1802 * Array axis summations, :py:func:`numpy.sum`. 1803 * Transpositions and permutations, :py:func:`numpy.transpose`. 1804 * Matrix multiplication and dot product, :py:func:`numpy.matmul` :py:func:`numpy.dot`. 1805 * Vector inner and outer products, :py:func:`numpy.inner` :py:func:`numpy.outer`. 1806 * Broadcasting, element-wise and scalar multiplication, :py:func:`numpy.multiply`. 1807 * Tensor contractions, :py:func:`numpy.tensordot`. 1808 * Chained array operations, in efficient calculation order, :py:func:`numpy.einsum_path`. 1809 1810 The subscripts string is a comma-separated list of subscript labels, 1811 where each label refers to a dimension of the corresponding operand. 1812 Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)`` 1813 is equivalent to :py:func:`np.inner(a,b) <numpy.inner>`. If a label 1814 appears only once, it is not summed, so ``np.einsum('i', a)`` produces a 1815 view of ``a`` with no changes. A further example ``np.einsum('ij,jk', a, b)`` 1816 describes traditional matrix multiplication and is equivalent to 1817 :py:func:`np.matmul(a,b) <numpy.matmul>`. Repeated subscript labels in one 1818 operand take the diagonal. For example, ``np.einsum('ii', a)`` is equivalent 1819 to :py:func:`np.trace(a) <numpy.trace>`. 1820 1821 In *implicit mode*, the chosen subscripts are important 1822 since the axes of the output are reordered alphabetically. This 1823 means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while 1824 ``np.einsum('ji', a)`` takes its transpose. Additionally, 1825 ``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while, 1826 ``np.einsum('ij,jh', a, b)`` returns the transpose of the 1827 multiplication since subscript 'h' precedes subscript 'i'. 1828 1829 In *explicit mode* the output can be directly controlled by 1830 specifying output subscript labels. This requires the 1831 identifier '->' as well as the list of output subscript labels. 1832 This feature increases the flexibility of the function since 1833 summing can be disabled or forced when required. The call 1834 ``np.einsum('i->', a)`` is like :py:func:`np.sum(a, axis=-1) <numpy.sum>`, 1835 and ``np.einsum('ii->i', a)`` is like :py:func:`np.diag(a) <numpy.diag>`. 1836 The difference is that `einsum` does not allow broadcasting by default. 1837 Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the 1838 order of the output subscript labels and therefore returns matrix 1839 multiplication, unlike the example above in implicit mode. 1840 1841 To enable and control broadcasting, use an ellipsis. Default 1842 NumPy-style broadcasting is done by adding an ellipsis 1843 to the left of each term, like ``np.einsum('...ii->...i', a)``. 1844 To take the trace along the first and last axes, 1845 you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix 1846 product with the left-most indices instead of rightmost, one can do 1847 ``np.einsum('ij...,jk...->ik...', a, b)``. 1848 1849 When there is only one operand, no axes are summed, and no output 1850 parameter is provided, a view into the operand is returned instead 1851 of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)`` 1852 produces a view (changed in version 1.10.0). 1853 1854 `einsum` also provides an alternative way to provide the subscripts 1855 and operands as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``. 1856 If the output shape is not provided in this format `einsum` will be 1857 calculated in implicit mode, otherwise it will be performed explicitly. 1858 The examples below have corresponding `einsum` calls with the two 1859 parameter methods. 1860 1861 .. versionadded:: 1.10.0 1862 1863 Views returned from einsum are now writeable whenever the input array 1864 is writeable. For example, ``np.einsum('ijk...->kji...', a)`` will now 1865 have the same effect as :py:func:`np.swapaxes(a, 0, 2) <numpy.swapaxes>` 1866 and ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal 1867 of a 2D array. 1868 1869 Examples 1870 -------- 1871 >>> a = np.arange(25).reshape(5,5) 1872 >>> b = np.arange(5) 1873 >>> c = np.arange(6).reshape(2,3) 1874 1875 Trace of a matrix: 1876 1877 >>> np.einsum('ii', a) 1878 60 1879 >>> np.einsum(a, [0,0]) 1880 60 1881 >>> np.trace(a) 1882 60 1883 1884 Extract the diagonal (requires explicit form): 1885 1886 >>> np.einsum('ii->i', a) 1887 array([ 0, 6, 12, 18, 24]) 1888 >>> np.einsum(a, [0,0], [0]) 1889 array([ 0, 6, 12, 18, 24]) 1890 >>> np.diag(a) 1891 array([ 0, 6, 12, 18, 24]) 1892 1893 Sum over an axis (requires explicit form): 1894 1895 >>> np.einsum('ij->i', a) 1896 array([ 10, 35, 60, 85, 110]) 1897 >>> np.einsum(a, [0,1], [0]) 1898 array([ 10, 35, 60, 85, 110]) 1899 >>> np.sum(a, axis=1) 1900 array([ 10, 35, 60, 85, 110]) 1901 1902 For higher dimensional arrays summing a single axis can be done with ellipsis: 1903 1904 >>> np.einsum('...j->...', a) 1905 array([ 10, 35, 60, 85, 110]) 1906 >>> np.einsum(a, [Ellipsis,1], [Ellipsis]) 1907 array([ 10, 35, 60, 85, 110]) 1908 1909 Compute a matrix transpose, or reorder any number of axes: 1910 1911 >>> np.einsum('ji', c) 1912 array([[0, 3], 1913 [1, 4], 1914 [2, 5]]) 1915 >>> np.einsum('ij->ji', c) 1916 array([[0, 3], 1917 [1, 4], 1918 [2, 5]]) 1919 >>> np.einsum(c, [1,0]) 1920 array([[0, 3], 1921 [1, 4], 1922 [2, 5]]) 1923 >>> np.transpose(c) 1924 array([[0, 3], 1925 [1, 4], 1926 [2, 5]]) 1927 1928 Vector inner products: 1929 1930 >>> np.einsum('i,i', b, b) 1931 30 1932 >>> np.einsum(b, [0], b, [0]) 1933 30 1934 >>> np.inner(b,b) 1935 30 1936 1937 Matrix vector multiplication: 1938 1939 >>> np.einsum('ij,j', a, b) 1940 array([ 30, 80, 130, 180, 230]) 1941 >>> np.einsum(a, [0,1], b, [1]) 1942 array([ 30, 80, 130, 180, 230]) 1943 >>> np.dot(a, b) 1944 array([ 30, 80, 130, 180, 230]) 1945 >>> np.einsum('...j,j', a, b) 1946 array([ 30, 80, 130, 180, 230]) 1947 1948 Broadcasting and scalar multiplication: 1949 1950 >>> np.einsum('..., ...', 3, c) 1951 array([[ 0, 3, 6], 1952 [ 9, 12, 15]]) 1953 >>> np.einsum(',ij', 3, c) 1954 array([[ 0, 3, 6], 1955 [ 9, 12, 15]]) 1956 >>> np.einsum(3, [Ellipsis], c, [Ellipsis]) 1957 array([[ 0, 3, 6], 1958 [ 9, 12, 15]]) 1959 >>> np.multiply(3, c) 1960 array([[ 0, 3, 6], 1961 [ 9, 12, 15]]) 1962 1963 Vector outer product: 1964 1965 >>> np.einsum('i,j', np.arange(2)+1, b) 1966 array([[0, 1, 2, 3, 4], 1967 [0, 2, 4, 6, 8]]) 1968 >>> np.einsum(np.arange(2)+1, [0], b, [1]) 1969 array([[0, 1, 2, 3, 4], 1970 [0, 2, 4, 6, 8]]) 1971 >>> np.outer(np.arange(2)+1, b) 1972 array([[0, 1, 2, 3, 4], 1973 [0, 2, 4, 6, 8]]) 1974 1975 Tensor contraction: 1976 1977 >>> a = np.arange(60.).reshape(3,4,5) 1978 >>> b = np.arange(24.).reshape(4,3,2) 1979 >>> np.einsum('ijk,jil->kl', a, b) 1980 array([[ 4400., 4730.], 1981 [ 4532., 4874.], 1982 [ 4664., 5018.], 1983 [ 4796., 5162.], 1984 [ 4928., 5306.]]) 1985 >>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3]) 1986 array([[ 4400., 4730.], 1987 [ 4532., 4874.], 1988 [ 4664., 5018.], 1989 [ 4796., 5162.], 1990 [ 4928., 5306.]]) 1991 >>> np.tensordot(a,b, axes=([1,0],[0,1])) 1992 array([[ 4400., 4730.], 1993 [ 4532., 4874.], 1994 [ 4664., 5018.], 1995 [ 4796., 5162.], 1996 [ 4928., 5306.]]) 1997 1998 Writeable returned arrays (since version 1.10.0): 1999 2000 >>> a = np.zeros((3, 3)) 2001 >>> np.einsum('ii->i', a)[:] = 1 2002 >>> a 2003 array([[ 1., 0., 0.], 2004 [ 0., 1., 0.], 2005 [ 0., 0., 1.]]) 2006 2007 Example of ellipsis use: 2008 2009 >>> a = np.arange(6).reshape((3,2)) 2010 >>> b = np.arange(12).reshape((4,3)) 2011 >>> np.einsum('ki,jk->ij', a, b) 2012 array([[10, 28, 46, 64], 2013 [13, 40, 67, 94]]) 2014 >>> np.einsum('ki,...k->i...', a, b) 2015 array([[10, 28, 46, 64], 2016 [13, 40, 67, 94]]) 2017 >>> np.einsum('k...,jk', a, b) 2018 array([[10, 28, 46, 64], 2019 [13, 40, 67, 94]]) 2020 2021 �ndarrayae 2022 ndarray(shape, dtype=float, buffer=None, offset=0, 2023 strides=None, order=None) 2024 2025 An array object represents a multidimensional, homogeneous array 2026 of fixed-size items. An associated data-type object describes the 2027 format of each element in the array (its byte-order, how many bytes it 2028 occupies in memory, whether it is an integer, a floating point number, 2029 or something else, etc.) 2030 2031 Arrays should be constructed using `array`, `zeros` or `empty` (refer 2032 to the See Also section below). The parameters given here refer to 2033 a low-level method (`ndarray(...)`) for instantiating an array. 2034 2035 For more information, refer to the `numpy` module and examine the 2036 methods and attributes of an array. 2037 2038 Parameters 2039 ---------- 2040 (for the __new__ method; see Notes below) 2041 2042 shape : tuple of ints 2043 Shape of created array. 2044 dtype : data-type, optional 2045 Any object that can be interpreted as a numpy data type. 2046 buffer : object exposing buffer interface, optional 2047 Used to fill the array with data. 2048 offset : int, optional 2049 Offset of array data in buffer. 2050 strides : tuple of ints, optional 2051 Strides of data in memory. 2052 order : {'C', 'F'}, optional 2053 Row-major (C-style) or column-major (Fortran-style) order. 2054 2055 Attributes 2056 ---------- 2057 T : ndarray 2058 Transpose of the array. 2059 data : buffer 2060 The array's elements, in memory. 2061 dtype : dtype object 2062 Describes the format of the elements in the array. 2063 flags : dict 2064 Dictionary containing information related to memory use, e.g., 2065 'C_CONTIGUOUS', 'OWNDATA', 'WRITEABLE', etc. 2066 flat : numpy.flatiter object 2067 Flattened version of the array as an iterator. The iterator 2068 allows assignments, e.g., ``x.flat = 3`` (See `ndarray.flat` for 2069 assignment examples; TODO). 2070 imag : ndarray 2071 Imaginary part of the array. 2072 real : ndarray 2073 Real part of the array. 2074 size : int 2075 Number of elements in the array. 2076 itemsize : int 2077 The memory use of each array element in bytes. 2078 nbytes : int 2079 The total number of bytes required to store the array data, 2080 i.e., ``itemsize * size``. 2081 ndim : int 2082 The array's number of dimensions. 2083 shape : tuple of ints 2084 Shape of the array. 2085 strides : tuple of ints 2086 The step-size required to move from one element to the next in 2087 memory. For example, a contiguous ``(3, 4)`` array of type 2088 ``int16`` in C-order has strides ``(8, 2)``. This implies that 2089 to move from element to element in memory requires jumps of 2 bytes. 2090 To move from row-to-row, one needs to jump 8 bytes at a time 2091 (``2 * 4``). 2092 ctypes : ctypes object 2093 Class containing properties of the array needed for interaction 2094 with ctypes. 2095 base : ndarray 2096 If the array is a view into another array, that array is its `base` 2097 (unless that array is also a view). The `base` array is where the 2098 array data is actually stored. 2099 2100 See Also 2101 -------- 2102 array : Construct an array. 2103 zeros : Create an array, each element of which is zero. 2104 empty : Create an array, but leave its allocated memory unchanged (i.e., 2105 it contains "garbage"). 2106 dtype : Create a data-type. 2107 numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>` 2108 w.r.t. its `dtype.type <numpy.dtype.type>`. 2109 2110 Notes 2111 ----- 2112 There are two modes of creating an array using ``__new__``: 2113 2114 1. If `buffer` is None, then only `shape`, `dtype`, and `order` 2115 are used. 2116 2. If `buffer` is an object exposing the buffer interface, then 2117 all keywords are interpreted. 2118 2119 No ``__init__`` method is needed because the array is fully initialized 2120 after the ``__new__`` method. 2121 2122 Examples 2123 -------- 2124 These examples illustrate the low-level `ndarray` constructor. Refer 2125 to the `See Also` section above for easier ways of constructing an 2126 ndarray. 2127 2128 First mode, `buffer` is None: 2129 2130 >>> np.ndarray(shape=(2,2), dtype=float, order='F') 2131 array([[0.0e+000, 0.0e+000], # random 2132 [ nan, 2.5e-323]]) 2133 2134 Second mode: 2135 2136 >>> np.ndarray((2,), buffer=np.array([1,2,3]), 2137 ... offset=np.int_().itemsize, 2138 ... dtype=int) # offset = 1*itemsize, i.e. skip first element 2139 array([2, 3]) 2140 2141 )�__array_interface__zArray protocol: Python side.)�__array_priority__zArray priority.)�__array_struct__zArray protocol: C-struct side.)� 2142 __dlpack__zIa.__dlpack__(*, stream=None) 2143 2144 DLPack Protocol: Part of the Array API.)�__dlpack_device__zBa.__dlpack_device__() 2145 2146 DLPack Protocol: Part of the Array API.)r a: 2147 Base object if memory is from some other object. 2148 2149 Examples 2150 -------- 2151 The base of an array that owns its memory is None: 2152 2153 >>> x = np.array([1,2,3,4]) 2154 >>> x.base is None 2155 True 2156 2157 Slicing creates a view, whose memory is shared with x: 2158 2159 >>> y = x[2:] 2160 >>> y.base is x 2161 True 2162 2163 )�ctypesa 2164 An object to simplify the interaction of the array with the ctypes 2165 module. 2166 2167 This attribute creates an object that makes it easier to use arrays 2168 when calling shared libraries with the ctypes module. The returned 2169 object has, among others, data, shape, and strides attributes (see 2170 Notes below) which themselves return ctypes objects that can be used 2171 as arguments to a shared library. 2172 2173 Parameters 2174 ---------- 2175 None 2176 2177 Returns 2178 ------- 2179 c : Python object 2180 Possessing attributes data, shape, strides, etc. 2181 2182 See Also 2183 -------- 2184 numpy.ctypeslib 2185 2186 Notes 2187 ----- 2188 Below are the public attributes of this object which were documented 2189 in "Guide to NumPy" (we have omitted undocumented public attributes, 2190 as well as documented private attributes): 2191 2192 .. autoattribute:: numpy.core._internal._ctypes.data 2193 :noindex: 2194 2195 .. autoattribute:: numpy.core._internal._ctypes.shape 2196 :noindex: 2197 2198 .. autoattribute:: numpy.core._internal._ctypes.strides 2199 :noindex: 2200 2201 .. automethod:: numpy.core._internal._ctypes.data_as 2202 :noindex: 2203 2204 .. automethod:: numpy.core._internal._ctypes.shape_as 2205 :noindex: 2206 2207 .. automethod:: numpy.core._internal._ctypes.strides_as 2208 :noindex: 2209 2210 If the ctypes module is not available, then the ctypes attribute 2211 of array objects still returns something useful, but ctypes objects 2212 are not returned and errors may be raised instead. In particular, 2213 the object will still have the ``as_parameter`` attribute which will 2214 return an integer equal to the data attribute. 2215 2216 Examples 2217 -------- 2218 >>> import ctypes 2219 >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32) 2220 >>> x 2221 array([[0, 1], 2222 [2, 3]], dtype=int32) 2223 >>> x.ctypes.data 2224 31962608 # may vary 2225 >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)) 2226 <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary 2227 >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents 2228 c_uint(0) 2229 >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents 2230 c_ulong(4294967296) 2231 >>> x.ctypes.shape 2232 <numpy.core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary 2233 >>> x.ctypes.strides 2234 <numpy.core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary 2235 2236 )�dataz?Python buffer object pointing to the start of the array's data.)�dtypea� 2237 Data-type of the array's elements. 2238 2239 .. warning:: 2240 2241 Setting ``arr.dtype`` is discouraged and may be deprecated in the 2242 future. Setting will replace the ``dtype`` without modifying the 2243 memory (see also `ndarray.view` and `ndarray.astype`). 2244 2245 Parameters 2246 ---------- 2247 None 2248 2249 Returns 2250 ------- 2251 d : numpy dtype object 2252 2253 See Also 2254 -------- 2255 ndarray.astype : Cast the values contained in the array to a new data-type. 2256 ndarray.view : Create a view of the same data but a different data-type. 2257 numpy.dtype 2258 2259 Examples 2260 -------- 2261 >>> x 2262 array([[0, 1], 2263 [2, 3]]) 2264 >>> x.dtype 2265 dtype('int32') 2266 >>> type(x.dtype) 2267 <type 'numpy.dtype'> 2268 2269 )�imagz� 2270 The imaginary part of the array. 2271 2272 Examples 2273 -------- 2274 >>> x = np.sqrt([1+0j, 0+1j]) 2275 >>> x.imag 2276 array([ 0. , 0.70710678]) 2277 >>> x.imag.dtype 2278 dtype('float64') 2279 2280 )�itemsizez� 2281 Length of one array element in bytes. 2282 2283 Examples 2284 -------- 2285 >>> x = np.array([1,2,3], dtype=np.float64) 2286 >>> x.itemsize 2287 8 2288 >>> x = np.array([1,2,3], dtype=np.complex128) 2289 >>> x.itemsize 2290 16 2291 2292 )�flagsa� 2293 Information about the memory layout of the array. 2294 2295 Attributes 2296 ---------- 2297 C_CONTIGUOUS (C) 2298 The data is in a single, C-style contiguous segment. 2299 F_CONTIGUOUS (F) 2300 The data is in a single, Fortran-style contiguous segment. 2301 OWNDATA (O) 2302 The array owns the memory it uses or borrows it from another object. 2303 WRITEABLE (W) 2304 The data area can be written to. Setting this to False locks 2305 the data, making it read-only. A view (slice, etc.) inherits WRITEABLE 2306 from its base array at creation time, but a view of a writeable 2307 array may be subsequently locked while the base array remains writeable. 2308 (The opposite is not true, in that a view of a locked array may not 2309 be made writeable. However, currently, locking a base object does not 2310 lock any views that already reference it, so under that circumstance it 2311 is possible to alter the contents of a locked array via a previously 2312 created writeable view onto it.) Attempting to change a non-writeable 2313 array raises a RuntimeError exception. 2314 ALIGNED (A) 2315 The data and all elements are aligned appropriately for the hardware. 2316 WRITEBACKIFCOPY (X) 2317 This array is a copy of some other array. The C-API function 2318 PyArray_ResolveWritebackIfCopy must be called before deallocating 2319 to the base array will be updated with the contents of this array. 2320 FNC 2321 F_CONTIGUOUS and not C_CONTIGUOUS. 2322 FORC 2323 F_CONTIGUOUS or C_CONTIGUOUS (one-segment test). 2324 BEHAVED (B) 2325 ALIGNED and WRITEABLE. 2326 CARRAY (CA) 2327 BEHAVED and C_CONTIGUOUS. 2328 FARRAY (FA) 2329 BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS. 2330 2331 Notes 2332 ----- 2333 The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``), 2334 or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag 2335 names are only supported in dictionary access. 2336 2337 Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be 2338 changed by the user, via direct assignment to the attribute or dictionary 2339 entry, or by calling `ndarray.setflags`. 2340 2341 The array flags cannot be set arbitrarily: 2342 2343 - WRITEBACKIFCOPY can only be set ``False``. 2344 - ALIGNED can only be set ``True`` if the data is truly aligned. 2345 - WRITEABLE can only be set ``True`` if the array owns its own memory 2346 or the ultimate owner of the memory exposes a writeable buffer 2347 interface or is a string. 2348 2349 Arrays can be both C-style and Fortran-style contiguous simultaneously. 2350 This is clear for 1-dimensional arrays, but can also be true for higher 2351 dimensional arrays. 2352 2353 Even for contiguous arrays a stride for a given dimension 2354 ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1`` 2355 or the array has no elements. 2356 It does *not* generally hold that ``self.strides[-1] == self.itemsize`` 2357 for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for 2358 Fortran-style contiguous arrays is true. 2359 )�flata� 2360 A 1-D iterator over the array. 2361 2362 This is a `numpy.flatiter` instance, which acts similarly to, but is not 2363 a subclass of, Python's built-in iterator object. 2364 2365 See Also 2366 -------- 2367 flatten : Return a copy of the array collapsed into one dimension. 2368 2369 flatiter 2370 2371 Examples 2372 -------- 2373 >>> x = np.arange(1, 7).reshape(2, 3) 2374 >>> x 2375 array([[1, 2, 3], 2376 [4, 5, 6]]) 2377 >>> x.flat[3] 2378 4 2379 >>> x.T 2380 array([[1, 4], 2381 [2, 5], 2382 [3, 6]]) 2383 >>> x.T.flat[3] 2384 5 2385 >>> type(x.flat) 2386 <class 'numpy.flatiter'> 2387 2388 An assignment example: 2389 2390 >>> x.flat = 3; x 2391 array([[3, 3, 3], 2392 [3, 3, 3]]) 2393 >>> x.flat[[1,4]] = 1; x 2394 array([[3, 1, 3], 2395 [3, 1, 3]]) 2396 2397 )�nbytesa? 2398 Total bytes consumed by the elements of the array. 2399 2400 Notes 2401 ----- 2402 Does not include memory consumed by non-element attributes of the 2403 array object. 2404 2405 Examples 2406 -------- 2407 >>> x = np.zeros((3,5,2), dtype=np.complex128) 2408 >>> x.nbytes 2409 480 2410 >>> np.prod(x.shape) * x.itemsize 2411 480 2412 2413 )r z� 2414 Number of array dimensions. 2415 2416 Examples 2417 -------- 2418 >>> x = np.array([1, 2, 3]) 2419 >>> x.ndim 2420 1 2421 >>> y = np.zeros((2, 3, 4)) 2422 >>> y.ndim 2423 3 2424 2425 )�reala 2426 The real part of the array. 2427 2428 Examples 2429 -------- 2430 >>> x = np.sqrt([1+0j, 0+1j]) 2431 >>> x.real 2432 array([ 1. , 0.70710678]) 2433 >>> x.real.dtype 2434 dtype('float64') 2435 2436 See Also 2437 -------- 2438 numpy.real : equivalent function 2439 2440 )r a 2441 Tuple of array dimensions. 2442 2443 The shape property is usually used to get the current shape of an array, 2444 but may also be used to reshape the array in-place by assigning a tuple of 2445 array dimensions to it. As with `numpy.reshape`, one of the new shape 2446 dimensions can be -1, in which case its value is inferred from the size of 2447 the array and the remaining dimensions. Reshaping an array in-place will 2448 fail if a copy is required. 2449 2450 .. warning:: 2451 2452 Setting ``arr.shape`` is discouraged and may be deprecated in the 2453 future. Using `ndarray.reshape` is the preferred approach. 2454 2455 Examples 2456 -------- 2457 >>> x = np.array([1, 2, 3, 4]) 2458 >>> x.shape 2459 (4,) 2460 >>> y = np.zeros((2, 3, 4)) 2461 >>> y.shape 2462 (2, 3, 4) 2463 >>> y.shape = (3, 8) 2464 >>> y 2465 array([[ 0., 0., 0., 0., 0., 0., 0., 0.], 2466 [ 0., 0., 0., 0., 0., 0., 0., 0.], 2467 [ 0., 0., 0., 0., 0., 0., 0., 0.]]) 2468 >>> y.shape = (3, 6) 2469 Traceback (most recent call last): 2470 File "<stdin>", line 1, in <module> 2471 ValueError: total size of new array must be unchanged 2472 >>> np.zeros((4,2))[::2].shape = (-1,) 2473 Traceback (most recent call last): 2474 File "<stdin>", line 1, in <module> 2475 AttributeError: Incompatible shape for in-place modification. Use 2476 `.reshape()` to make a copy with the desired shape. 2477 2478 See Also 2479 -------- 2480 numpy.shape : Equivalent getter function. 2481 numpy.reshape : Function similar to setting ``shape``. 2482 ndarray.reshape : Method similar to setting ``shape``. 2483 2484 )r az 2485 Number of elements in the array. 2486 2487 Equal to ``np.prod(a.shape)``, i.e., the product of the array's 2488 dimensions. 2489 2490 Notes 2491 ----- 2492 `a.size` returns a standard arbitrary precision Python integer. This 2493 may not be the case with other methods of obtaining the same value 2494 (like the suggested ``np.prod(a.shape)``, which returns an instance 2495 of ``np.int_``), and may be relevant if the value is used further in 2496 calculations that may overflow a fixed size integer type. 2497 2498 Examples 2499 -------- 2500 >>> x = np.zeros((3, 5, 2), dtype=np.complex128) 2501 >>> x.size 2502 30 2503 >>> np.prod(x.shape) 2504 30 2505 2506 )�stridesa{ 2507 Tuple of bytes to step in each dimension when traversing an array. 2508 2509 The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a` 2510 is:: 2511 2512 offset = sum(np.array(i) * a.strides) 2513 2514 A more detailed explanation of strides can be found in the 2515 "ndarray.rst" file in the NumPy reference guide. 2516 2517 .. warning:: 2518 2519 Setting ``arr.strides`` is discouraged and may be deprecated in the 2520 future. `numpy.lib.stride_tricks.as_strided` should be preferred 2521 to create a new view of the same data in a safer way. 2522 2523 Notes 2524 ----- 2525 Imagine an array of 32-bit integers (each 4 bytes):: 2526 2527 x = np.array([[0, 1, 2, 3, 4], 2528 [5, 6, 7, 8, 9]], dtype=np.int32) 2529 2530 This array is stored in memory as 40 bytes, one after the other 2531 (known as a contiguous block of memory). The strides of an array tell 2532 us how many bytes we have to skip in memory to move to the next position 2533 along a certain axis. For example, we have to skip 4 bytes (1 value) to 2534 move to the next column, but 20 bytes (5 values) to get to the same 2535 position in the next row. As such, the strides for the array `x` will be 2536 ``(20, 4)``. 2537 2538 See Also 2539 -------- 2540 numpy.lib.stride_tricks.as_strided 2541 2542 Examples 2543 -------- 2544 >>> y = np.reshape(np.arange(2*3*4), (2,3,4)) 2545 >>> y 2546 array([[[ 0, 1, 2, 3], 2547 [ 4, 5, 6, 7], 2548 [ 8, 9, 10, 11]], 2549 [[12, 13, 14, 15], 2550 [16, 17, 18, 19], 2551 [20, 21, 22, 23]]]) 2552 >>> y.strides 2553 (48, 16, 4) 2554 >>> y[1,1,1] 2555 17 2556 >>> offset=sum(y.strides * np.array((1,1,1))) 2557 >>> offset/y.itemsize 2558 17 2559 2560 >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0) 2561 >>> x.strides 2562 (32, 4, 224, 1344) 2563 >>> i = np.array([3,5,2,2]) 2564 >>> offset = sum(i * x.strides) 2565 >>> x[3,5,2,2] 2566 813 2567 >>> offset / x.itemsize 2568 813 2569 2570 )�Ta� 2571 View of the transposed array. 2572 2573 Same as ``self.transpose()``. 2574 2575 Examples 2576 -------- 2577 >>> a = np.array([[1, 2], [3, 4]]) 2578 >>> a 2579 array([[1, 2], 2580 [3, 4]]) 2581 >>> a.T 2582 array([[1, 3], 2583 [2, 4]]) 2584 2585 >>> a = np.array([1, 2, 3, 4]) 2586 >>> a 2587 array([1, 2, 3, 4]) 2588 >>> a.T 2589 array([1, 2, 3, 4]) 2590 2591 See Also 2592 -------- 2593 transpose 2594 2595 )r z� a.__array__([dtype], /) -> reference if type unchanged, copy otherwise. 2596 2597 Returns either a new reference to self if dtype is not given or a new array 2598 of provided data type if dtype is different from the current dtype of the 2599 array. 2600 2601 )�__array_finalize__z[a.__array_finalize__(obj, /) 2602 2603 Present so subclasses can call super. Does nothing. 2604 2605 )�__array_prepare__zia.__array_prepare__(array[, context], /) 2606 2607 Returns a view of `array` with the same type as self. 2608 2609 )�__array_wrap__zfa.__array_wrap__(array[, context], /) 2610 2611 Returns a view of `array` with the same type as self. 2612 2613 )�__copy__z�a.__copy__() 2614 2615 Used if :func:`copy.copy` is called on an array. Returns a copy of the array. 2616 2617 Equivalent to ``a.copy(order='K')``. 2618 2619 )�__class_getitem__a� a.__class_getitem__(item, /) 2620 2621 Return a parametrized wrapper around the `~numpy.ndarray` type. 2622 2623 .. versionadded:: 1.22 2624 2625 Returns 2626 ------- 2627 alias : types.GenericAlias 2628 A parametrized `~numpy.ndarray` type. 2629 2630 Examples 2631 -------- 2632 >>> from typing import Any 2633 >>> import numpy as np 2634 2635 >>> np.ndarray[Any, np.dtype[Any]] 2636 numpy.ndarray[typing.Any, numpy.dtype[typing.Any]] 2637 2638 Notes 2639 ----- 2640 This method is only available for python 3.9 and later. 2641 2642 See Also 2643 -------- 2644 :pep:`585` : Type hinting generics in standard collections. 2645 numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>` 2646 w.r.t. its `dtype.type <numpy.dtype.type>`. 2647 2648 )�__deepcopy__zna.__deepcopy__(memo, /) -> Deep copy of array. 2649 2650 Used if :func:`copy.deepcopy` is called on an array. 2651 2652 )� 2653 __reduce__z'a.__reduce__() 2654 2655 For pickling. 2656 2657 )�__setstate__a� a.__setstate__(state, /) 2658 2659 For unpickling. 2660 2661 The `state` argument must be a sequence that contains the following 2662 elements: 2663 2664 Parameters 2665 ---------- 2666 version : int 2667 optional pickle version. If omitted defaults to 0. 2668 shape : tuple 2669 dtype : data-type 2670 isFortran : bool 2671 rawdata : string or list 2672 a binary string with the data (or a list if 'a' is an object array) 2673 2674 )�allz� 2675 a.all(axis=None, out=None, keepdims=False, *, where=True) 2676 2677 Returns True if all elements evaluate to True. 2678 2679 Refer to `numpy.all` for full documentation. 2680 2681 See Also 2682 -------- 2683 numpy.all : equivalent function 2684 2685 )�anyz� 2686 a.any(axis=None, out=None, keepdims=False, *, where=True) 2687 2688 Returns True if any of the elements of `a` evaluate to True. 2689 2690 Refer to `numpy.any` for full documentation. 2691 2692 See Also 2693 -------- 2694 numpy.any : equivalent function 2695 2696 )�argmaxz� 2697 a.argmax(axis=None, out=None, *, keepdims=False) 2698 2699 Return indices of the maximum values along the given axis. 2700 2701 Refer to `numpy.argmax` for full documentation. 2702 2703 See Also 2704 -------- 2705 numpy.argmax : equivalent function 2706 2707 )�argminz� 2708 a.argmin(axis=None, out=None, *, keepdims=False) 2709 2710 Return indices of the minimum values along the given axis. 2711 2712 Refer to `numpy.argmin` for detailed documentation. 2713 2714 See Also 2715 -------- 2716 numpy.argmin : equivalent function 2717 2718 )�argsortz� 2719 a.argsort(axis=-1, kind=None, order=None) 2720 2721 Returns the indices that would sort this array. 2722 2723 Refer to `numpy.argsort` for full documentation. 2724 2725 See Also 2726 -------- 2727 numpy.argsort : equivalent function 2728 2729 )�argpartitiona! 2730 a.argpartition(kth, axis=-1, kind='introselect', order=None) 2731 2732 Returns the indices that would partition this array. 2733 2734 Refer to `numpy.argpartition` for full documentation. 2735 2736 .. versionadded:: 1.8.0 2737 2738 See Also 2739 -------- 2740 numpy.argpartition : equivalent function 2741 2742 )�astypea} 2743 2744 a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True) 2745 2746 Copy of the array, cast to a specified type. 2747 2748 Parameters 2749 ---------- 2750 dtype : str or dtype 2751 Typecode or data-type to which the array is cast. 2752 order : {'C', 'F', 'A', 'K'}, optional 2753 Controls the memory layout order of the result. 2754 'C' means C order, 'F' means Fortran order, 'A' 2755 means 'F' order if all the arrays are Fortran contiguous, 2756 'C' order otherwise, and 'K' means as close to the 2757 order the array elements appear in memory as possible. 2758 Default is 'K'. 2759 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional 2760 Controls what kind of data casting may occur. Defaults to 'unsafe' 2761 for backwards compatibility. 2762 2763 * 'no' means the data types should not be cast at all. 2764 * 'equiv' means only byte-order changes are allowed. 2765 * 'safe' means only casts which can preserve values are allowed. 2766 * 'same_kind' means only safe casts or casts within a kind, 2767 like float64 to float32, are allowed. 2768 * 'unsafe' means any data conversions may be done. 2769 subok : bool, optional 2770 If True, then sub-classes will be passed-through (default), otherwise 2771 the returned array will be forced to be a base-class array. 2772 copy : bool, optional 2773 By default, astype always returns a newly allocated array. If this 2774 is set to false, and the `dtype`, `order`, and `subok` 2775 requirements are satisfied, the input array is returned instead 2776 of a copy. 2777 2778 Returns 2779 ------- 2780 arr_t : ndarray 2781 Unless `copy` is False and the other conditions for returning the input 2782 array are satisfied (see description for `copy` input parameter), `arr_t` 2783 is a new array of the same shape as the input array, with dtype, order 2784 given by `dtype`, `order`. 2785 2786 Notes 2787 ----- 2788 .. versionchanged:: 1.17.0 2789 Casting between a simple data type and a structured one is possible only 2790 for "unsafe" casting. Casting to multiple fields is allowed, but 2791 casting from multiple fields is not. 2792 2793 .. versionchanged:: 1.9.0 2794 Casting from numeric to string types in 'safe' casting mode requires 2795 that the string dtype length is long enough to store the max 2796 integer/float value converted. 2797 2798 Raises 2799 ------ 2800 ComplexWarning 2801 When casting from complex to float or int. To avoid this, 2802 one should use ``a.real.astype(t)``. 2803 2804 Examples 2805 -------- 2806 >>> x = np.array([1, 2, 2.5]) 2807 >>> x 2808 array([1. , 2. , 2.5]) 2809 2810 >>> x.astype(int) 2811 array([1, 2, 2]) 2812 2813 )�byteswapa� 2814 a.byteswap(inplace=False) 2815 2816 Swap the bytes of the array elements 2817 2818 Toggle between low-endian and big-endian data representation by 2819 returning a byteswapped array, optionally swapped in-place. 2820 Arrays of byte-strings are not swapped. The real and imaginary 2821 parts of a complex number are swapped individually. 2822 2823 Parameters 2824 ---------- 2825 inplace : bool, optional 2826 If ``True``, swap bytes in-place, default is ``False``. 2827 2828 Returns 2829 ------- 2830 out : ndarray 2831 The byteswapped array. If `inplace` is ``True``, this is 2832 a view to self. 2833 2834 Examples 2835 -------- 2836 >>> A = np.array([1, 256, 8755], dtype=np.int16) 2837 >>> list(map(hex, A)) 2838 ['0x1', '0x100', '0x2233'] 2839 >>> A.byteswap(inplace=True) 2840 array([ 256, 1, 13090], dtype=int16) 2841 >>> list(map(hex, A)) 2842 ['0x100', '0x1', '0x3322'] 2843 2844 Arrays of byte-strings are not swapped 2845 2846 >>> A = np.array([b'ceg', b'fac']) 2847 >>> A.byteswap() 2848 array([b'ceg', b'fac'], dtype='|S3') 2849 2850 ``A.newbyteorder().byteswap()`` produces an array with the same values 2851 but different representation in memory 2852 2853 >>> A = np.array([1, 2, 3]) 2854 >>> A.view(np.uint8) 2855 array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 2856 0, 0], dtype=uint8) 2857 >>> A.newbyteorder().byteswap(inplace=True) 2858 array([1, 2, 3]) 2859 >>> A.view(np.uint8) 2860 array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 2861 0, 3], dtype=uint8) 2862 2863 )�choosez� 2864 a.choose(choices, out=None, mode='raise') 2865 2866 Use an index array to construct a new array from a set of choices. 2867 2868 Refer to `numpy.choose` for full documentation. 2869 2870 See Also 2871 -------- 2872 numpy.choose : equivalent function 2873 2874 )�clipa 2875 a.clip(min=None, max=None, out=None, **kwargs) 2876 2877 Return an array whose values are limited to ``[min, max]``. 2878 One of max or min must be given. 2879 2880 Refer to `numpy.clip` for full documentation. 2881 2882 See Also 2883 -------- 2884 numpy.clip : equivalent function 2885 2886 )�compressz� 2887 a.compress(condition, axis=None, out=None) 2888 2889 Return selected slices of this array along given axis. 2890 2891 Refer to `numpy.compress` for full documentation. 2892 2893 See Also 2894 -------- 2895 numpy.compress : equivalent function 2896 2897 )�conjz� 2898 a.conj() 2899 2900 Complex-conjugate all elements. 2901 2902 Refer to `numpy.conjugate` for full documentation. 2903 2904 See Also 2905 -------- 2906 numpy.conjugate : equivalent function 2907 2908 )� conjugatez� 2909 a.conjugate() 2910 2911 Return the complex conjugate, element-wise. 2912 2913 Refer to `numpy.conjugate` for full documentation. 2914 2915 See Also 2916 -------- 2917 numpy.conjugate : equivalent function 2918 2919 )r a� 2920 a.copy(order='C') 2921 2922 Return a copy of the array. 2923 2924 Parameters 2925 ---------- 2926 order : {'C', 'F', 'A', 'K'}, optional 2927 Controls the memory layout of the copy. 'C' means C-order, 2928 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 2929 'C' otherwise. 'K' means match the layout of `a` as closely 2930 as possible. (Note that this function and :func:`numpy.copy` are very 2931 similar but have different default values for their order= 2932 arguments, and this function always passes sub-classes through.) 2933 2934 See also 2935 -------- 2936 numpy.copy : Similar function with different default behavior 2937 numpy.copyto 2938 2939 Notes 2940 ----- 2941 This function is the preferred method for creating an array copy. The 2942 function :func:`numpy.copy` is similar, but it defaults to using order 'K', 2943 and will not pass sub-classes through by default. 2944 2945 Examples 2946 -------- 2947 >>> x = np.array([[1,2,3],[4,5,6]], order='F') 2948 2949 >>> y = x.copy() 2950 2951 >>> x.fill(0) 2952 2953 >>> x 2954 array([[0, 0, 0], 2955 [0, 0, 0]]) 2956 2957 >>> y 2958 array([[1, 2, 3], 2959 [4, 5, 6]]) 2960 2961 >>> y.flags['C_CONTIGUOUS'] 2962 True 2963 2964 )�cumprodz� 2965 a.cumprod(axis=None, dtype=None, out=None) 2966 2967 Return the cumulative product of the elements along the given axis. 2968 2969 Refer to `numpy.cumprod` for full documentation. 2970 2971 See Also 2972 -------- 2973 numpy.cumprod : equivalent function 2974 2975 )�cumsumz� 2976 a.cumsum(axis=None, dtype=None, out=None) 2977 2978 Return the cumulative sum of the elements along the given axis. 2979 2980 Refer to `numpy.cumsum` for full documentation. 2981 2982 See Also 2983 -------- 2984 numpy.cumsum : equivalent function 2985 2986 )�diagonala� 2987 a.diagonal(offset=0, axis1=0, axis2=1) 2988 2989 Return specified diagonals. In NumPy 1.9 the returned array is a 2990 read-only view instead of a copy as in previous NumPy versions. In 2991 a future version the read-only restriction will be removed. 2992 2993 Refer to :func:`numpy.diagonal` for full documentation. 2994 2995 See Also 2996 -------- 2997 numpy.diagonal : equivalent function 2998 2999 �dot)�dumpa> a.dump(file) 3000 3001 Dump a pickle of the array to the specified file. 3002 The array can be read back with pickle.load or numpy.load. 3003 3004 Parameters 3005 ---------- 3006 file : str or Path 3007 A string naming the dump file. 3008 3009 .. versionchanged:: 1.17.0 3010 `pathlib.Path` objects are now accepted. 3011 3012 )�dumpsz� 3013 a.dumps() 3014 3015 Returns the pickle of the array as a string. 3016 pickle.loads will convert the string back to an array. 3017 3018 Parameters 3019 ---------- 3020 None 3021 3022 )�fillaw 3023 a.fill(value) 3024 3025 Fill the array with a scalar value. 3026 3027 Parameters 3028 ---------- 3029 value : scalar 3030 All elements of `a` will be assigned this value. 3031 3032 Examples 3033 -------- 3034 >>> a = np.array([1, 2]) 3035 >>> a.fill(0) 3036 >>> a 3037 array([0, 0]) 3038 >>> a = np.empty(2) 3039 >>> a.fill(1) 3040 >>> a 3041 array([1., 1.]) 3042 3043 Fill expects a scalar value and always behaves the same as assigning 3044 to a single array element. The following is a rare example where this 3045 distinction is important: 3046 3047 >>> a = np.array([None, None], dtype=object) 3048 >>> a[0] = np.array(3) 3049 >>> a 3050 array([array(3), None], dtype=object) 3051 >>> a.fill(np.array(3)) 3052 >>> a 3053 array([array(3), array(3)], dtype=object) 3054 3055 Where other forms of assignments will unpack the array being assigned: 3056 3057 >>> a[...] = np.array(3) 3058 >>> a 3059 array([3, 3], dtype=object) 3060 3061 )�flattena� 3062 a.flatten(order='C') 3063 3064 Return a copy of the array collapsed into one dimension. 3065 3066 Parameters 3067 ---------- 3068 order : {'C', 'F', 'A', 'K'}, optional 3069 'C' means to flatten in row-major (C-style) order. 3070 'F' means to flatten in column-major (Fortran- 3071 style) order. 'A' means to flatten in column-major 3072 order if `a` is Fortran *contiguous* in memory, 3073 row-major order otherwise. 'K' means to flatten 3074 `a` in the order the elements occur in memory. 3075 The default is 'C'. 3076 3077 Returns 3078 ------- 3079 y : ndarray 3080 A copy of the input array, flattened to one dimension. 3081 3082 See Also 3083 -------- 3084 ravel : Return a flattened array. 3085 flat : A 1-D flat iterator over the array. 3086 3087 Examples 3088 -------- 3089 >>> a = np.array([[1,2], [3,4]]) 3090 >>> a.flatten() 3091 array([1, 2, 3, 4]) 3092 >>> a.flatten('F') 3093 array([1, 3, 2, 4]) 3094 3095 )�getfielda� 3096 a.getfield(dtype, offset=0) 3097 3098 Returns a field of the given array as a certain type. 3099 3100 A field is a view of the array data with a given data-type. The values in 3101 the view are determined by the given type and the offset into the current 3102 array in bytes. The offset needs to be such that the view dtype fits in the 3103 array dtype; for example an array of dtype complex128 has 16-byte elements. 3104 If taking a view with a 32-bit integer (4 bytes), the offset needs to be 3105 between 0 and 12 bytes. 3106 3107 Parameters 3108 ---------- 3109 dtype : str or dtype 3110 The data type of the view. The dtype size of the view can not be larger 3111 than that of the array itself. 3112 offset : int 3113 Number of bytes to skip before beginning the element view. 3114 3115 Examples 3116 -------- 3117 >>> x = np.diag([1.+1.j]*2) 3118 >>> x[1, 1] = 2 + 4.j 3119 >>> x 3120 array([[1.+1.j, 0.+0.j], 3121 [0.+0.j, 2.+4.j]]) 3122 >>> x.getfield(np.float64) 3123 array([[1., 0.], 3124 [0., 2.]]) 3125 3126 By choosing an offset of 8 bytes we can select the complex part of the 3127 array for our view: 3128 3129 >>> x.getfield(np.float64, offset=8) 3130 array([[1., 0.], 3131 [0., 4.]]) 3132 3133 )�itema� 3134 a.item(*args) 3135 3136 Copy an element of an array to a standard Python scalar and return it. 3137 3138 Parameters 3139 ---------- 3140 \*args : Arguments (variable number and type) 3141 3142 * none: in this case, the method only works for arrays 3143 with one element (`a.size == 1`), which element is 3144 copied into a standard Python scalar object and returned. 3145 3146 * int_type: this argument is interpreted as a flat index into 3147 the array, specifying which element to copy and return. 3148 3149 * tuple of int_types: functions as does a single int_type argument, 3150 except that the argument is interpreted as an nd-index into the 3151 array. 3152 3153 Returns 3154 ------- 3155 z : Standard Python scalar object 3156 A copy of the specified element of the array as a suitable 3157 Python scalar 3158 3159 Notes 3160 ----- 3161 When the data type of `a` is longdouble or clongdouble, item() returns 3162 a scalar array object because there is no available Python scalar that 3163 would not lose information. Void arrays return a buffer object for item(), 3164 unless fields are defined, in which case a tuple is returned. 3165 3166 `item` is very similar to a[args], except, instead of an array scalar, 3167 a standard Python scalar is returned. This can be useful for speeding up 3168 access to elements of the array and doing arithmetic on elements of the 3169 array using Python's optimized math. 3170 3171 Examples 3172 -------- 3173 >>> np.random.seed(123) 3174 >>> x = np.random.randint(9, size=(3, 3)) 3175 >>> x 3176 array([[2, 2, 6], 3177 [1, 3, 6], 3178 [1, 0, 1]]) 3179 >>> x.item(3) 3180 1 3181 >>> x.item(7) 3182 0 3183 >>> x.item((0, 1)) 3184 2 3185 >>> x.item((2, 2)) 3186 1 3187 3188 )�itemseta� 3189 a.itemset(*args) 3190 3191 Insert scalar into an array (scalar is cast to array's dtype, if possible) 3192 3193 There must be at least 1 argument, and define the last argument 3194 as *item*. Then, ``a.itemset(*args)`` is equivalent to but faster 3195 than ``a[args] = item``. The item should be a scalar value and `args` 3196 must select a single item in the array `a`. 3197 3198 Parameters 3199 ---------- 3200 \*args : Arguments 3201 If one argument: a scalar, only used in case `a` is of size 1. 3202 If two arguments: the last argument is the value to be set 3203 and must be a scalar, the first argument specifies a single array 3204 element location. It is either an int or a tuple. 3205 3206 Notes 3207 ----- 3208 Compared to indexing syntax, `itemset` provides some speed increase 3209 for placing a scalar into a particular location in an `ndarray`, 3210 if you must do this. However, generally this is discouraged: 3211 among other problems, it complicates the appearance of the code. 3212 Also, when using `itemset` (and `item`) inside a loop, be sure 3213 to assign the methods to a local variable to avoid the attribute 3214 look-up at each loop iteration. 3215 3216 Examples 3217 -------- 3218 >>> np.random.seed(123) 3219 >>> x = np.random.randint(9, size=(3, 3)) 3220 >>> x 3221 array([[2, 2, 6], 3222 [1, 3, 6], 3223 [1, 0, 1]]) 3224 >>> x.itemset(4, 0) 3225 >>> x.itemset((2, 2), 9) 3226 >>> x 3227 array([[2, 2, 6], 3228 [1, 0, 6], 3229 [1, 0, 9]]) 3230 3231 )�maxz� 3232 a.max(axis=None, out=None, keepdims=False, initial=<no value>, where=True) 3233 3234 Return the maximum along a given axis. 3235 3236 Refer to `numpy.amax` for full documentation. 3237 3238 See Also 3239 -------- 3240 numpy.amax : equivalent function 3241 3242 )�meana 3243 a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True) 3244 3245 Returns the average of the array elements along given axis. 3246 3247 Refer to `numpy.mean` for full documentation. 3248 3249 See Also 3250 -------- 3251 numpy.mean : equivalent function 3252 3253 )�minz� 3254 a.min(axis=None, out=None, keepdims=False, initial=<no value>, where=True) 3255 3256 Return the minimum along a given axis. 3257 3258 Refer to `numpy.amin` for full documentation. 3259 3260 See Also 3261 -------- 3262 numpy.amin : equivalent function 3263 3264 )�newbyteordera� 3265 arr.newbyteorder(new_order='S', /) 3266 3267 Return the array with the same data viewed with a different byte order. 3268 3269 Equivalent to:: 3270 3271 arr.view(arr.dtype.newbytorder(new_order)) 3272 3273 Changes are also made in all fields and sub-arrays of the array data 3274 type. 3275 3276 3277 3278 Parameters 3279 ---------- 3280 new_order : string, optional 3281 Byte order to force; a value from the byte order specifications 3282 below. `new_order` codes can be any of: 3283 3284 * 'S' - swap dtype from current to opposite endian 3285 * {'<', 'little'} - little endian 3286 * {'>', 'big'} - big endian 3287 * {'=', 'native'} - native order, equivalent to `sys.byteorder` 3288 * {'|', 'I'} - ignore (no change to byte order) 3289 3290 The default value ('S') results in swapping the current 3291 byte order. 3292 3293 3294 Returns 3295 ------- 3296 new_arr : array 3297 New array object with the dtype reflecting given change to the 3298 byte order. 3299 3300 )�nonzeroz� 3301 a.nonzero() 3302 3303 Return the indices of the elements that are non-zero. 3304 3305 Refer to `numpy.nonzero` for full documentation. 3306 3307 See Also 3308 -------- 3309 numpy.nonzero : equivalent function 3310 3311 )�proda 3312 a.prod(axis=None, dtype=None, out=None, keepdims=False, initial=1, where=True) 3313 3314 Return the product of the array elements over the given axis 3315 3316 Refer to `numpy.prod` for full documentation. 3317 3318 See Also 3319 -------- 3320 numpy.prod : equivalent function 3321 3322 )�ptpz� 3323 a.ptp(axis=None, out=None, keepdims=False) 3324 3325 Peak to peak (maximum - minimum) value along a given axis. 3326 3327 Refer to `numpy.ptp` for full documentation. 3328 3329 See Also 3330 -------- 3331 numpy.ptp : equivalent function 3332 3333 )�putz� 3334 a.put(indices, values, mode='raise') 3335 3336 Set ``a.flat[n] = values[n]`` for all `n` in indices. 3337 3338 Refer to `numpy.put` for full documentation. 3339 3340 See Also 3341 -------- 3342 numpy.put : equivalent function 3343 3344 )�ravelz� 3345 a.ravel([order]) 3346 3347 Return a flattened array. 3348 3349 Refer to `numpy.ravel` for full documentation. 3350 3351 See Also 3352 -------- 3353 numpy.ravel : equivalent function 3354 3355 ndarray.flat : a flat iterator on the array. 3356 3357 )�repeatz� 3358 a.repeat(repeats, axis=None) 3359 3360 Repeat elements of an array. 3361 3362 Refer to `numpy.repeat` for full documentation. 3363 3364 See Also 3365 -------- 3366 numpy.repeat : equivalent function 3367 3368 )�reshapea� 3369 a.reshape(shape, order='C') 3370 3371 Returns an array containing the same data with a new shape. 3372 3373 Refer to `numpy.reshape` for full documentation. 3374 3375 See Also 3376 -------- 3377 numpy.reshape : equivalent function 3378 3379 Notes 3380 ----- 3381 Unlike the free function `numpy.reshape`, this method on `ndarray` allows 3382 the elements of the shape parameter to be passed in as separate arguments. 3383 For example, ``a.reshape(10, 11)`` is equivalent to 3384 ``a.reshape((10, 11))``. 3385 3386 )�resizeaB 3387 a.resize(new_shape, refcheck=True) 3388 3389 Change shape and size of array in-place. 3390 3391 Parameters 3392 ---------- 3393 new_shape : tuple of ints, or `n` ints 3394 Shape of resized array. 3395 refcheck : bool, optional 3396 If False, reference count will not be checked. Default is True. 3397 3398 Returns 3399 ------- 3400 None 3401 3402 Raises 3403 ------ 3404 ValueError 3405 If `a` does not own its own data or references or views to it exist, 3406 and the data memory must be changed. 3407 PyPy only: will always raise if the data memory must be changed, since 3408 there is no reliable way to determine if references or views to it 3409 exist. 3410 3411 SystemError 3412 If the `order` keyword argument is specified. This behaviour is a 3413 bug in NumPy. 3414 3415 See Also 3416 -------- 3417 resize : Return a new array with the specified shape. 3418 3419 Notes 3420 ----- 3421 This reallocates space for the data area if necessary. 3422 3423 Only contiguous arrays (data elements consecutive in memory) can be 3424 resized. 3425 3426 The purpose of the reference count check is to make sure you 3427 do not use this array as a buffer for another Python object and then 3428 reallocate the memory. However, reference counts can increase in 3429 other ways so if you are sure that you have not shared the memory 3430 for this array with another Python object, then you may safely set 3431 `refcheck` to False. 3432 3433 Examples 3434 -------- 3435 Shrinking an array: array is flattened (in the order that the data are 3436 stored in memory), resized, and reshaped: 3437 3438 >>> a = np.array([[0, 1], [2, 3]], order='C') 3439 >>> a.resize((2, 1)) 3440 >>> a 3441 array([[0], 3442 [1]]) 3443 3444 >>> a = np.array([[0, 1], [2, 3]], order='F') 3445 >>> a.resize((2, 1)) 3446 >>> a 3447 array([[0], 3448 [2]]) 3449 3450 Enlarging an array: as above, but missing entries are filled with zeros: 3451 3452 >>> b = np.array([[0, 1], [2, 3]]) 3453 >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple 3454 >>> b 3455 array([[0, 1, 2], 3456 [3, 0, 0]]) 3457 3458 Referencing an array prevents resizing... 3459 3460 >>> c = a 3461 >>> a.resize((1, 1)) 3462 Traceback (most recent call last): 3463 ... 3464 ValueError: cannot resize an array that references or is referenced ... 3465 3466 Unless `refcheck` is False: 3467 3468 >>> a.resize((1, 1), refcheck=False) 3469 >>> a 3470 array([[0]]) 3471 >>> c 3472 array([[0]]) 3473 3474 )�roundz� 3475 a.round(decimals=0, out=None) 3476 3477 Return `a` with each element rounded to the given number of decimals. 3478 3479 Refer to `numpy.around` for full documentation. 3480 3481 See Also 3482 -------- 3483 numpy.around : equivalent function 3484 3485 )�searchsorteda 3486 a.searchsorted(v, side='left', sorter=None) 3487 3488 Find indices where elements of v should be inserted in a to maintain order. 3489 3490 For full documentation, see `numpy.searchsorted` 3491 3492 See Also 3493 -------- 3494 numpy.searchsorted : equivalent function 3495 3496 )�setfieldaj 3497 a.setfield(val, dtype, offset=0) 3498 3499 Put a value into a specified place in a field defined by a data-type. 3500 3501 Place `val` into `a`'s field defined by `dtype` and beginning `offset` 3502 bytes into the field. 3503 3504 Parameters 3505 ---------- 3506 val : object 3507 Value to be placed in field. 3508 dtype : dtype object 3509 Data-type of the field in which to place `val`. 3510 offset : int, optional 3511 The number of bytes into the field at which to place `val`. 3512 3513 Returns 3514 ------- 3515 None 3516 3517 See Also 3518 -------- 3519 getfield 3520 3521 Examples 3522 -------- 3523 >>> x = np.eye(3) 3524 >>> x.getfield(np.float64) 3525 array([[1., 0., 0.], 3526 [0., 1., 0.], 3527 [0., 0., 1.]]) 3528 >>> x.setfield(3, np.int32) 3529 >>> x.getfield(np.int32) 3530 array([[3, 3, 3], 3531 [3, 3, 3], 3532 [3, 3, 3]], dtype=int32) 3533 >>> x 3534 array([[1.0e+000, 1.5e-323, 1.5e-323], 3535 [1.5e-323, 1.0e+000, 1.5e-323], 3536 [1.5e-323, 1.5e-323, 1.0e+000]]) 3537 >>> x.setfield(np.eye(3), np.int32) 3538 >>> x 3539 array([[1., 0., 0.], 3540 [0., 1., 0.], 3541 [0., 0., 1.]]) 3542 3543 )�setflagsa� 3544 a.setflags(write=None, align=None, uic=None) 3545 3546 Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY, 3547 respectively. 3548 3549 These Boolean-valued flags affect how numpy interprets the memory 3550 area used by `a` (see Notes below). The ALIGNED flag can only 3551 be set to True if the data is actually aligned according to the type. 3552 The WRITEBACKIFCOPY and flag can never be set 3553 to True. The flag WRITEABLE can only be set to True if the array owns its 3554 own memory, or the ultimate owner of the memory exposes a writeable buffer 3555 interface, or is a string. (The exception for string is made so that 3556 unpickling can be done without copying memory.) 3557 3558 Parameters 3559 ---------- 3560 write : bool, optional 3561 Describes whether or not `a` can be written to. 3562 align : bool, optional 3563 Describes whether or not `a` is aligned properly for its type. 3564 uic : bool, optional 3565 Describes whether or not `a` is a copy of another "base" array. 3566 3567 Notes 3568 ----- 3569 Array flags provide information about how the memory area used 3570 for the array is to be interpreted. There are 7 Boolean flags 3571 in use, only four of which can be changed by the user: 3572 WRITEBACKIFCOPY, WRITEABLE, and ALIGNED. 3573 3574 WRITEABLE (W) the data area can be written to; 3575 3576 ALIGNED (A) the data and strides are aligned appropriately for the hardware 3577 (as determined by the compiler); 3578 3579 WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced 3580 by .base). When the C-API function PyArray_ResolveWritebackIfCopy is 3581 called, the base array will be updated with the contents of this array. 3582 3583 All flags can be accessed using the single (upper case) letter as well 3584 as the full name. 3585 3586 Examples 3587 -------- 3588 >>> y = np.array([[3, 1, 7], 3589 ... [2, 0, 0], 3590 ... [8, 5, 9]]) 3591 >>> y 3592 array([[3, 1, 7], 3593 [2, 0, 0], 3594 [8, 5, 9]]) 3595 >>> y.flags 3596 C_CONTIGUOUS : True 3597 F_CONTIGUOUS : False 3598 OWNDATA : True 3599 WRITEABLE : True 3600 ALIGNED : True 3601 WRITEBACKIFCOPY : False 3602 >>> y.setflags(write=0, align=0) 3603 >>> y.flags 3604 C_CONTIGUOUS : True 3605 F_CONTIGUOUS : False 3606 OWNDATA : True 3607 WRITEABLE : False 3608 ALIGNED : False 3609 WRITEBACKIFCOPY : False 3610 >>> y.setflags(uic=1) 3611 Traceback (most recent call last): 3612 File "<stdin>", line 1, in <module> 3613 ValueError: cannot set WRITEBACKIFCOPY flag to True 3614 3615 )�sorta� 3616 a.sort(axis=-1, kind=None, order=None) 3617 3618 Sort an array in-place. Refer to `numpy.sort` for full documentation. 3619 3620 Parameters 3621 ---------- 3622 axis : int, optional 3623 Axis along which to sort. Default is -1, which means sort along the 3624 last axis. 3625 kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional 3626 Sorting algorithm. The default is 'quicksort'. Note that both 'stable' 3627 and 'mergesort' use timsort under the covers and, in general, the 3628 actual implementation will vary with datatype. The 'mergesort' option 3629 is retained for backwards compatibility. 3630 3631 .. versionchanged:: 1.15.0 3632 The 'stable' option was added. 3633 3634 order : str or list of str, optional 3635 When `a` is an array with fields defined, this argument specifies 3636 which fields to compare first, second, etc. A single field can 3637 be specified as a string, and not all fields need be specified, 3638 but unspecified fields will still be used, in the order in which 3639 they come up in the dtype, to break ties. 3640 3641 See Also 3642 -------- 3643 numpy.sort : Return a sorted copy of an array. 3644 numpy.argsort : Indirect sort. 3645 numpy.lexsort : Indirect stable sort on multiple keys. 3646 numpy.searchsorted : Find elements in sorted array. 3647 numpy.partition: Partial sort. 3648 3649 Notes 3650 ----- 3651 See `numpy.sort` for notes on the different sorting algorithms. 3652 3653 Examples 3654 -------- 3655 >>> a = np.array([[1,4], [3,1]]) 3656 >>> a.sort(axis=1) 3657 >>> a 3658 array([[1, 4], 3659 [1, 3]]) 3660 >>> a.sort(axis=0) 3661 >>> a 3662 array([[1, 3], 3663 [1, 4]]) 3664 3665 Use the `order` keyword to specify a field to use when sorting a 3666 structured array: 3667 3668 >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)]) 3669 >>> a.sort(order='y') 3670 >>> a 3671 array([(b'c', 1), (b'a', 2)], 3672 dtype=[('x', 'S1'), ('y', '<i8')]) 3673 3674 )� partitiona� 3675 a.partition(kth, axis=-1, kind='introselect', order=None) 3676 3677 Rearranges the elements in the array in such a way that the value of the 3678 element in kth position is in the position it would be in a sorted array. 3679 All elements smaller than the kth element are moved before this element and 3680 all equal or greater are moved behind it. The ordering of the elements in 3681 the two partitions is undefined. 3682 3683 .. versionadded:: 1.8.0 3684 3685 Parameters 3686 ---------- 3687 kth : int or sequence of ints 3688 Element index to partition by. The kth element value will be in its 3689 final sorted position and all smaller elements will be moved before it 3690 and all equal or greater elements behind it. 3691 The order of all elements in the partitions is undefined. 3692 If provided with a sequence of kth it will partition all elements 3693 indexed by kth of them into their sorted position at once. 3694 3695 .. deprecated:: 1.22.0 3696 Passing booleans as index is deprecated. 3697 axis : int, optional 3698 Axis along which to sort. Default is -1, which means sort along the 3699 last axis. 3700 kind : {'introselect'}, optional 3701 Selection algorithm. Default is 'introselect'. 3702 order : str or list of str, optional 3703 When `a` is an array with fields defined, this argument specifies 3704 which fields to compare first, second, etc. A single field can 3705 be specified as a string, and not all fields need to be specified, 3706 but unspecified fields will still be used, in the order in which 3707 they come up in the dtype, to break ties. 3708 3709 See Also 3710 -------- 3711 numpy.partition : Return a partitioned copy of an array. 3712 argpartition : Indirect partition. 3713 sort : Full sort. 3714 3715 Notes 3716 ----- 3717 See ``np.partition`` for notes on the different algorithms. 3718 3719 Examples 3720 -------- 3721 >>> a = np.array([3, 4, 2, 1]) 3722 >>> a.partition(3) 3723 >>> a 3724 array([2, 1, 3, 4]) 3725 3726 >>> a.partition((1, 3)) 3727 >>> a 3728 array([1, 2, 3, 4]) 3729 )�squeezez� 3730 a.squeeze(axis=None) 3731 3732 Remove axes of length one from `a`. 3733 3734 Refer to `numpy.squeeze` for full documentation. 3735 3736 See Also 3737 -------- 3738 numpy.squeeze : equivalent function 3739 3740 )�stda 3741 a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True) 3742 3743 Returns the standard deviation of the array elements along given axis. 3744 3745 Refer to `numpy.std` for full documentation. 3746 3747 See Also 3748 -------- 3749 numpy.std : equivalent function 3750 3751 )�suma 3752 a.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True) 3753 3754 Return the sum of the array elements over the given axis. 3755 3756 Refer to `numpy.sum` for full documentation. 3757 3758 See Also 3759 -------- 3760 numpy.sum : equivalent function 3761 3762 )�swapaxesz� 3763 a.swapaxes(axis1, axis2) 3764 3765 Return a view of the array with `axis1` and `axis2` interchanged. 3766 3767 Refer to `numpy.swapaxes` for full documentation. 3768 3769 See Also 3770 -------- 3771 numpy.swapaxes : equivalent function 3772 3773 )�takez� 3774 a.take(indices, axis=None, out=None, mode='raise') 3775 3776 Return an array formed from the elements of `a` at the given indices. 3777 3778 Refer to `numpy.take` for full documentation. 3779 3780 See Also 3781 -------- 3782 numpy.take : equivalent function 3783 3784 )�tofilea 3785 a.tofile(fid, sep="", format="%s") 3786 3787 Write array to a file as text or binary (default). 3788 3789 Data is always written in 'C' order, independent of the order of `a`. 3790 The data produced by this method can be recovered using the function 3791 fromfile(). 3792 3793 Parameters 3794 ---------- 3795 fid : file or str or Path 3796 An open file object, or a string containing a filename. 3797 3798 .. versionchanged:: 1.17.0 3799 `pathlib.Path` objects are now accepted. 3800 3801 sep : str 3802 Separator between array items for text output. 3803 If "" (empty), a binary file is written, equivalent to 3804 ``file.write(a.tobytes())``. 3805 format : str 3806 Format string for text file output. 3807 Each entry in the array is formatted to text by first converting 3808 it to the closest Python type, and then using "format" % item. 3809 3810 Notes 3811 ----- 3812 This is a convenience function for quick storage of array data. 3813 Information on endianness and precision is lost, so this method is not a 3814 good choice for files intended to archive data or transport data between 3815 machines with different endianness. Some of these problems can be overcome 3816 by outputting the data as text files, at the expense of speed and file 3817 size. 3818 3819 When fid is a file object, array contents are directly written to the 3820 file, bypassing the file object's ``write`` method. As a result, tofile 3821 cannot be used with files objects supporting compression (e.g., GzipFile) 3822 or file-like objects that do not support ``fileno()`` (e.g., BytesIO). 3823 3824 )�tolista 3825 a.tolist() 3826 3827 Return the array as an ``a.ndim``-levels deep nested list of Python scalars. 3828 3829 Return a copy of the array data as a (nested) Python list. 3830 Data items are converted to the nearest compatible builtin Python type, via 3831 the `~numpy.ndarray.item` function. 3832 3833 If ``a.ndim`` is 0, then since the depth of the nested list is 0, it will 3834 not be a list at all, but a simple Python scalar. 3835 3836 Parameters 3837 ---------- 3838 none 3839 3840 Returns 3841 ------- 3842 y : object, or list of object, or list of list of object, or ... 3843 The possibly nested list of array elements. 3844 3845 Notes 3846 ----- 3847 The array may be recreated via ``a = np.array(a.tolist())``, although this 3848 may sometimes lose precision. 3849 3850 Examples 3851 -------- 3852 For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``, 3853 except that ``tolist`` changes numpy scalars to Python scalars: 3854 3855 >>> a = np.uint32([1, 2]) 3856 >>> a_list = list(a) 3857 >>> a_list 3858 [1, 2] 3859 >>> type(a_list[0]) 3860 <class 'numpy.uint32'> 3861 >>> a_tolist = a.tolist() 3862 >>> a_tolist 3863 [1, 2] 3864 >>> type(a_tolist[0]) 3865 <class 'int'> 3866 3867 Additionally, for a 2D array, ``tolist`` applies recursively: 3868 3869 >>> a = np.array([[1, 2], [3, 4]]) 3870 >>> list(a) 3871 [array([1, 2]), array([3, 4])] 3872 >>> a.tolist() 3873 [[1, 2], [3, 4]] 3874 3875 The base case for this recursion is a 0D array: 3876 3877 >>> a = np.array(1) 3878 >>> list(a) 3879 Traceback (most recent call last): 3880 ... 3881 TypeError: iteration over a 0-d array 3882 >>> a.tolist() 3883 1 3884 )�tobytesa: 3885 a.tobytes(order='C') 3886 3887 Construct Python bytes containing the raw data bytes in the array. 3888 3889 Constructs Python bytes showing a copy of the raw contents of 3890 data memory. The bytes object is produced in C-order by default. 3891 This behavior is controlled by the ``order`` parameter. 3892 3893 .. versionadded:: 1.9.0 3894 3895 Parameters 3896 ---------- 3897 order : {'C', 'F', 'A'}, optional 3898 Controls the memory layout of the bytes object. 'C' means C-order, 3899 'F' means F-order, 'A' (short for *Any*) means 'F' if `a` is 3900 Fortran contiguous, 'C' otherwise. Default is 'C'. 3901 3902 Returns 3903 ------- 3904 s : bytes 3905 Python bytes exhibiting a copy of `a`'s raw data. 3906 3907 See also 3908 -------- 3909 frombuffer 3910 Inverse of this operation, construct a 1-dimensional array from Python 3911 bytes. 3912 3913 Examples 3914 -------- 3915 >>> x = np.array([[0, 1], [2, 3]], dtype='<u2') 3916 >>> x.tobytes() 3917 b'\x00\x00\x01\x00\x02\x00\x03\x00' 3918 >>> x.tobytes('C') == x.tobytes() 3919 True 3920 >>> x.tobytes('F') 3921 b'\x00\x00\x02\x00\x01\x00\x03\x00' 3922 3923 )�tostringz� 3924 a.tostring(order='C') 3925 3926 A compatibility alias for `tobytes`, with exactly the same behavior. 3927 3928 Despite its name, it returns `bytes` not `str`\ s. 3929 3930 .. deprecated:: 1.19.0 3931 )�tracez� 3932 a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None) 3933 3934 Return the sum along diagonals of the array. 3935 3936 Refer to `numpy.trace` for full documentation. 3937 3938 See Also 3939 -------- 3940 numpy.trace : equivalent function 3941 3942 )� transposea 3943 a.transpose(*axes) 3944 3945 Returns a view of the array with axes transposed. 3946 3947 Refer to `numpy.transpose` for full documentation. 3948 3949 Parameters 3950 ---------- 3951 axes : None, tuple of ints, or `n` ints 3952 3953 * None or no argument: reverses the order of the axes. 3954 3955 * tuple of ints: `i` in the `j`-th place in the tuple means that the 3956 array's `i`-th axis becomes the transposed array's `j`-th axis. 3957 3958 * `n` ints: same as an n-tuple of the same ints (this form is 3959 intended simply as a "convenience" alternative to the tuple form). 3960 3961 Returns 3962 ------- 3963 p : ndarray 3964 View of the array with its axes suitably permuted. 3965 3966 See Also 3967 -------- 3968 transpose : Equivalent function. 3969 ndarray.T : Array property returning the array transposed. 3970 ndarray.reshape : Give a new shape to an array without changing its data. 3971 3972 Examples 3973 -------- 3974 >>> a = np.array([[1, 2], [3, 4]]) 3975 >>> a 3976 array([[1, 2], 3977 [3, 4]]) 3978 >>> a.transpose() 3979 array([[1, 3], 3980 [2, 4]]) 3981 >>> a.transpose((1, 0)) 3982 array([[1, 3], 3983 [2, 4]]) 3984 >>> a.transpose(1, 0) 3985 array([[1, 3], 3986 [2, 4]]) 3987 3988 >>> a = np.array([1, 2, 3, 4]) 3989 >>> a 3990 array([1, 2, 3, 4]) 3991 >>> a.transpose() 3992 array([1, 2, 3, 4]) 3993 3994 )�vara 3995 a.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True) 3996 3997 Returns the variance of the array elements, along given axis. 3998 3999 Refer to `numpy.var` for full documentation. 4000 4001 See Also 4002 -------- 4003 numpy.var : equivalent function 4004 4005 )�viewa9 4006 a.view([dtype][, type]) 4007 4008 New view of array with the same data. 4009 4010 .. note:: 4011 Passing None for ``dtype`` is different from omitting the parameter, 4012 since the former invokes ``dtype(None)`` which is an alias for 4013 ``dtype('float_')``. 4014 4015 Parameters 4016 ---------- 4017 dtype : data-type or ndarray sub-class, optional 4018 Data-type descriptor of the returned view, e.g., float32 or int16. 4019 Omitting it results in the view having the same data-type as `a`. 4020 This argument can also be specified as an ndarray sub-class, which 4021 then specifies the type of the returned object (this is equivalent to 4022 setting the ``type`` parameter). 4023 type : Python type, optional 4024 Type of the returned view, e.g., ndarray or matrix. Again, omission 4025 of the parameter results in type preservation. 4026 4027 Notes 4028 ----- 4029 ``a.view()`` is used two different ways: 4030 4031 ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view 4032 of the array's memory with a different data-type. This can cause a 4033 reinterpretation of the bytes of memory. 4034 4035 ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just 4036 returns an instance of `ndarray_subclass` that looks at the same array 4037 (same shape, dtype, etc.) This does not cause a reinterpretation of the 4038 memory. 4039 4040 For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of 4041 bytes per entry than the previous dtype (for example, converting a regular 4042 array to a structured array), then the last axis of ``a`` must be 4043 contiguous. This axis will be resized in the result. 4044 4045 .. versionchanged:: 1.23.0 4046 Only the last axis needs to be contiguous. Previously, the entire array 4047 had to be C-contiguous. 4048 4049 Examples 4050 -------- 4051 >>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)]) 4052 4053 Viewing array data using a different type and dtype: 4054 4055 >>> y = x.view(dtype=np.int16, type=np.matrix) 4056 >>> y 4057 matrix([[513]], dtype=int16) 4058 >>> print(type(y)) 4059 <class 'numpy.matrix'> 4060 4061 Creating a view on a structured array so it can be used in calculations 4062 4063 >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)]) 4064 >>> xv = x.view(dtype=np.int8).reshape(-1,2) 4065 >>> xv 4066 array([[1, 2], 4067 [3, 4]], dtype=int8) 4068 >>> xv.mean(0) 4069 array([2., 3.]) 4070 4071 Making changes to the view changes the underlying array 4072 4073 >>> xv[0,1] = 20 4074 >>> x 4075 array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')]) 4076 4077 Using a view to convert an array to a recarray: 4078 4079 >>> z = x.view(np.recarray) 4080 >>> z.a 4081 array([1, 3], dtype=int8) 4082 4083 Views share data: 4084 4085 >>> x[0] = (9, 10) 4086 >>> z[0] 4087 (9, 10) 4088 4089 Views that change the dtype size (bytes per entry) should normally be 4090 avoided on arrays defined by slices, transposes, fortran-ordering, etc.: 4091 4092 >>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16) 4093 >>> y = x[:, ::2] 4094 >>> y 4095 array([[1, 3], 4096 [4, 6]], dtype=int16) 4097 >>> y.view(dtype=[('width', np.int16), ('length', np.int16)]) 4098 Traceback (most recent call last): 4099 ... 4100 ValueError: To change to a dtype of a different size, the last axis must be contiguous 4101 >>> z = y.copy() 4102 >>> z.view(dtype=[('width', np.int16), ('length', np.int16)]) 4103 array([[(1, 3)], 4104 [(4, 6)]], dtype=[('width', '<i2'), ('length', '<i2')]) 4105 4106 However, views that change dtype are totally fine for arrays with a 4107 contiguous last axis, even if the rest of the axes are not C-contiguous: 4108 4109 >>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4) 4110 >>> x.transpose(1, 0, 2).view(np.int16) 4111 array([[[ 256, 770], 4112 [3340, 3854]], 4113 <BLANKLINE> 4114 [[1284, 1798], 4115 [4368, 4882]], 4116 <BLANKLINE> 4117 [[2312, 2826], 4118 [5396, 5910]]], dtype=int16) 4119 4120 znumpy.core.umath� 4121 frompyfunca 4122 frompyfunc(func, /, nin, nout, *[, identity]) 4123 4124 Takes an arbitrary Python function and returns a NumPy ufunc. 4125 4126 Can be used, for example, to add broadcasting to a built-in Python 4127 function (see Examples section). 4128 4129 Parameters 4130 ---------- 4131 func : Python function object 4132 An arbitrary Python function. 4133 nin : int 4134 The number of input arguments. 4135 nout : int 4136 The number of objects returned by `func`. 4137 identity : object, optional 4138 The value to use for the `~numpy.ufunc.identity` attribute of the resulting 4139 object. If specified, this is equivalent to setting the underlying 4140 C ``identity`` field to ``PyUFunc_IdentityValue``. 4141 If omitted, the identity is set to ``PyUFunc_None``. Note that this is 4142 _not_ equivalent to setting the identity to ``None``, which implies the 4143 operation is reorderable. 4144 4145 Returns 4146 ------- 4147 out : ufunc 4148 Returns a NumPy universal function (``ufunc``) object. 4149 4150 See Also 4151 -------- 4152 vectorize : Evaluates pyfunc over input arrays using broadcasting rules of numpy. 4153 4154 Notes 4155 ----- 4156 The returned ufunc always returns PyObject arrays. 4157 4158 Examples 4159 -------- 4160 Use frompyfunc to add broadcasting to the Python function ``oct``: 4161 4162 >>> oct_array = np.frompyfunc(oct, 1, 1) 4163 >>> oct_array(np.array((10, 30, 100))) 4164 array(['0o12', '0o36', '0o144'], dtype=object) 4165 >>> np.array((oct(10), oct(30), oct(100))) # for comparison 4166 array(['0o12', '0o36', '0o144'], dtype='<U5') 4167 4168 � geterrobja� 4169 geterrobj() 4170 4171 Return the current object that defines floating-point error handling. 4172 4173 The error object contains all information that defines the error handling 4174 behavior in NumPy. `geterrobj` is used internally by the other 4175 functions that get and set error handling behavior (`geterr`, `seterr`, 4176 `geterrcall`, `seterrcall`). 4177 4178 Returns 4179 ------- 4180 errobj : list 4181 The error object, a list containing three elements: 4182 [internal numpy buffer size, error mask, error callback function]. 4183 4184 The error mask is a single integer that holds the treatment information 4185 on all four floating point errors. The information for each error type 4186 is contained in three bits of the integer. If we print it in base 8, we 4187 can see what treatment is set for "invalid", "under", "over", and 4188 "divide" (in that order). The printed string can be interpreted with 4189 4190 * 0 : 'ignore' 4191 * 1 : 'warn' 4192 * 2 : 'raise' 4193 * 3 : 'call' 4194 * 4 : 'print' 4195 * 5 : 'log' 4196 4197 See Also 4198 -------- 4199 seterrobj, seterr, geterr, seterrcall, geterrcall 4200 getbufsize, setbufsize 4201 4202 Notes 4203 ----- 4204 For complete documentation of the types of floating-point exceptions and 4205 treatment options, see `seterr`. 4206 4207 Examples 4208 -------- 4209 >>> np.geterrobj() # first get the defaults 4210 [8192, 521, None] 4211 4212 >>> def err_handler(type, flag): 4213 ... print("Floating point error (%s), with flag %s" % (type, flag)) 4214 ... 4215 >>> old_bufsize = np.setbufsize(20000) 4216 >>> old_err = np.seterr(divide='raise') 4217 >>> old_handler = np.seterrcall(err_handler) 4218 >>> np.geterrobj() 4219 [8192, 521, <function err_handler at 0x91dcaac>] 4220 4221 >>> old_err = np.seterr(all='ignore') 4222 >>> np.base_repr(np.geterrobj()[1], 8) 4223 '0' 4224 >>> old_err = np.seterr(divide='warn', over='log', under='call', 4225 ... invalid='print') 4226 >>> np.base_repr(np.geterrobj()[1], 8) 4227 '4351' 4228 4229 � seterrobja$ 4230 seterrobj(errobj, /) 4231 4232 Set the object that defines floating-point error handling. 4233 4234 The error object contains all information that defines the error handling 4235 behavior in NumPy. `seterrobj` is used internally by the other 4236 functions that set error handling behavior (`seterr`, `seterrcall`). 4237 4238 Parameters 4239 ---------- 4240 errobj : list 4241 The error object, a list containing three elements: 4242 [internal numpy buffer size, error mask, error callback function]. 4243 4244 The error mask is a single integer that holds the treatment information 4245 on all four floating point errors. The information for each error type 4246 is contained in three bits of the integer. If we print it in base 8, we 4247 can see what treatment is set for "invalid", "under", "over", and 4248 "divide" (in that order). The printed string can be interpreted with 4249 4250 * 0 : 'ignore' 4251 * 1 : 'warn' 4252 * 2 : 'raise' 4253 * 3 : 'call' 4254 * 4 : 'print' 4255 * 5 : 'log' 4256 4257 See Also 4258 -------- 4259 geterrobj, seterr, geterr, seterrcall, geterrcall 4260 getbufsize, setbufsize 4261 4262 Notes 4263 ----- 4264 For complete documentation of the types of floating-point exceptions and 4265 treatment options, see `seterr`. 4266 4267 Examples 4268 -------- 4269 >>> old_errobj = np.geterrobj() # first get the defaults 4270 >>> old_errobj 4271 [8192, 521, None] 4272 4273 >>> def err_handler(type, flag): 4274 ... print("Floating point error (%s), with flag %s" % (type, flag)) 4275 ... 4276 >>> new_errobj = [20000, 12, err_handler] 4277 >>> np.seterrobj(new_errobj) 4278 >>> np.base_repr(12, 8) # int for divide=4 ('print') and over=1 ('warn') 4279 '14' 4280 >>> np.geterr() 4281 {'over': 'warn', 'divide': 'print', 'invalid': 'ignore', 'under': 'ignore'} 4282 >>> np.geterrcall() is err_handler 4283 True 4284 4285 � add_docstringz� 4286 add_docstring(obj, docstring) 4287 4288 Add a docstring to a built-in obj if possible. 4289 If the obj already has a docstring raise a RuntimeError 4290 If this routine does not know how to add a docstring to the object 4291 raise a TypeError 4292 �_add_newdoc_ufuncaI 4293 add_ufunc_docstring(ufunc, new_docstring) 4294 4295 Replace the docstring for a ufunc with new_docstring. 4296 This method will only work if the current docstring for 4297 the ufunc is NULL. (At the C level, i.e. when ufunc->doc is NULL.) 4298 4299 Parameters 4300 ---------- 4301 ufunc : numpy.ufunc 4302 A ufunc whose current doc is NULL. 4303 new_docstring : string 4304 The new docstring for the ufunc. 4305 4306 Notes 4307 ----- 4308 This method allocates memory for new_docstring on 4309 the heap. Technically this creates a mempory leak, since this 4310 memory will not be reclaimed until the end of the program 4311 even if the ufunc itself is removed. However this will only 4312 be a problem if the user is repeatedly creating ufuncs with 4313 no documentation, adding documentation via add_newdoc_ufunc, 4314 and then throwing away the ufunc. 4315 �get_handler_nameah 4316 get_handler_name(a: ndarray) -> str,None 4317 4318 Return the name of the memory handler used by `a`. If not provided, return 4319 the name of the memory handler that will be used to allocate data for the 4320 next `ndarray` in this context. May return None if `a` does not own its 4321 memory, in which case you can traverse ``a.base`` for a memory handler. 4322 �get_handler_versionaq 4323 get_handler_version(a: ndarray) -> int,None 4324 4325 Return the version of the memory handler used by `a`. If not provided, 4326 return the version of the memory handler that will be used to allocate data 4327 for the next `ndarray` in this context. May return None if `a` does not own 4328 its memory, in which case you can traverse ``a.base`` for a memory handler. 4329 �_get_madvise_hugepagez� 4330 _get_madvise_hugepage() -> bool 4331 4332 Get use of ``madvise (2)`` MADV_HUGEPAGE support when 4333 allocating the array data. Returns the currently set value. 4334 See `global_state` for more information. 4335 �_set_madvise_hugepagez� 4336 _set_madvise_hugepage(enabled: bool) -> bool 4337 4338 Set or unset use of ``madvise (2)`` MADV_HUGEPAGE support when 4339 allocating the array data. Returns the previously set value. 4340 See `global_state` for more information. 4341 znumpy.core._multiarray_testsZformat_float_OSprintf_ga� 4342 format_float_OSprintf_g(val, precision) 4343 4344 Print a floating point scalar using the system's printf function, 4345 equivalent to: 4346 4347 printf("%.*g", precision, val); 4348 4349 for half/float/double, or replacing 'g' by 'Lg' for longdouble. This 4350 method is designed to help cross-validate the format_float_* methods. 4351 4352 Parameters 4353 ---------- 4354 val : python float or numpy floating scalar 4355 Value to format. 4356 4357 precision : non-negative integer, optional 4358 Precision given to printf. 4359 4360 Returns 4361 ------- 4362 rep : string 4363 The string representation of the floating point value 4364 4365 See Also 4366 -------- 4367 format_float_scientific 4368 format_float_positional 4369 �ufunca) 4370 Functions that operate element by element on whole arrays. 4371 4372 To see the documentation for a specific ufunc, use `info`. For 4373 example, ``np.info(np.sin)``. Because ufuncs are written in C 4374 (for speed) and linked into Python with NumPy's ufunc facility, 4375 Python's help() function finds this page whenever help() is called 4376 on a ufunc. 4377 4378 A detailed explanation of ufuncs can be found in the docs for :ref:`ufuncs`. 4379 4380 **Calling ufuncs:** ``op(*x[, out], where=True, **kwargs)`` 4381 4382 Apply `op` to the arguments `*x` elementwise, broadcasting the arguments. 4383 4384 The broadcasting rules are: 4385 4386 * Dimensions of length 1 may be prepended to either array. 4387 * Arrays may be repeated along dimensions of length 1. 4388 4389 Parameters 4390 ---------- 4391 *x : array_like 4392 Input arrays. 4393 out : ndarray, None, or tuple of ndarray and None, optional 4394 Alternate array object(s) in which to put the result; if provided, it 4395 must have a shape that the inputs broadcast to. A tuple of arrays 4396 (possible only as a keyword argument) must have length equal to the 4397 number of outputs; use None for uninitialized outputs to be 4398 allocated by the ufunc. 4399 where : array_like, optional 4400 This condition is broadcast over the input. At locations where the 4401 condition is True, the `out` array will be set to the ufunc result. 4402 Elsewhere, the `out` array will retain its original value. 4403 Note that if an uninitialized `out` array is created via the default 4404 ``out=None``, locations within it where the condition is False will 4405 remain uninitialized. 4406 **kwargs 4407 For other keyword-only arguments, see the :ref:`ufunc docs <ufuncs.kwargs>`. 4408 4409 Returns 4410 ------- 4411 r : ndarray or tuple of ndarray 4412 `r` will have the shape that the arrays in `x` broadcast to; if `out` is 4413 provided, it will be returned. If not, `r` will be allocated and 4414 may contain uninitialized values. If the function has more than one 4415 output, then the result will be a tuple of arrays. 4416 4417 )�identityaD 4418 The identity value. 4419 4420 Data attribute containing the identity element for the ufunc, if it has one. 4421 If it does not, the attribute value is None. 4422 4423 Examples 4424 -------- 4425 >>> np.add.identity 4426 0 4427 >>> np.multiply.identity 4428 1 4429 >>> np.power.identity 4430 1 4431 >>> print(np.exp.identity) 4432 None 4433 )�nargsa� 4434 The number of arguments. 4435 4436 Data attribute containing the number of arguments the ufunc takes, including 4437 optional ones. 4438 4439 Notes 4440 ----- 4441 Typically this value will be one more than what you might expect because all 4442 ufuncs take the optional "out" argument. 4443 4444 Examples 4445 -------- 4446 >>> np.add.nargs 4447 3 4448 >>> np.multiply.nargs 4449 3 4450 >>> np.power.nargs 4451 3 4452 >>> np.exp.nargs 4453 2 4454 )�ninz� 4455 The number of inputs. 4456 4457 Data attribute containing the number of arguments the ufunc treats as input. 4458 4459 Examples 4460 -------- 4461 >>> np.add.nin 4462 2 4463 >>> np.multiply.nin 4464 2 4465 >>> np.power.nin 4466 2 4467 >>> np.exp.nin 4468 1 4469 )�noutae 4470 The number of outputs. 4471 4472 Data attribute containing the number of arguments the ufunc treats as output. 4473 4474 Notes 4475 ----- 4476 Since all ufuncs can take output arguments, this will always be (at least) 1. 4477 4478 Examples 4479 -------- 4480 >>> np.add.nout 4481 1 4482 >>> np.multiply.nout 4483 1 4484 >>> np.power.nout 4485 1 4486 >>> np.exp.nout 4487 1 4488 4489 )�ntypesau 4490 The number of types. 4491 4492 The number of numerical NumPy types - of which there are 18 total - on which 4493 the ufunc can operate. 4494 4495 See Also 4496 -------- 4497 numpy.ufunc.types 4498 4499 Examples 4500 -------- 4501 >>> np.add.ntypes 4502 18 4503 >>> np.multiply.ntypes 4504 18 4505 >>> np.power.ntypes 4506 17 4507 >>> np.exp.ntypes 4508 7 4509 >>> np.remainder.ntypes 4510 14 4511 4512 )�typesa\ 4513 Returns a list with types grouped input->output. 4514 4515 Data attribute listing the data-type "Domain-Range" groupings the ufunc can 4516 deliver. The data-types are given using the character codes. 4517 4518 See Also 4519 -------- 4520 numpy.ufunc.ntypes 4521 4522 Examples 4523 -------- 4524 >>> np.add.types 4525 ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 4526 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 4527 'GG->G', 'OO->O'] 4528 4529 >>> np.multiply.types 4530 ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 4531 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 4532 'GG->G', 'OO->O'] 4533 4534 >>> np.power.types 4535 ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 4536 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G', 4537 'OO->O'] 4538 4539 >>> np.exp.types 4540 ['f->f', 'd->d', 'g->g', 'F->F', 'D->D', 'G->G', 'O->O'] 4541 4542 >>> np.remainder.types 4543 ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 4544 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'OO->O'] 4545 4546 )� signatureaz 4547 Definition of the core elements a generalized ufunc operates on. 4548 4549 The signature determines how the dimensions of each input/output array 4550 are split into core and loop dimensions: 4551 4552 1. Each dimension in the signature is matched to a dimension of the 4553 corresponding passed-in array, starting from the end of the shape tuple. 4554 2. Core dimensions assigned to the same label in the signature must have 4555 exactly matching sizes, no broadcasting is performed. 4556 3. The core dimensions are removed from all inputs and the remaining 4557 dimensions are broadcast together, defining the loop dimensions. 4558 4559 Notes 4560 ----- 4561 Generalized ufuncs are used internally in many linalg functions, and in 4562 the testing suite; the examples below are taken from these. 4563 For ufuncs that operate on scalars, the signature is None, which is 4564 equivalent to '()' for every argument. 4565 4566 Examples 4567 -------- 4568 >>> np.core.umath_tests.matrix_multiply.signature 4569 '(m,n),(n,p)->(m,p)' 4570 >>> np.linalg._umath_linalg.det.signature 4571 '(m,m)->()' 4572 >>> np.add.signature is None 4573 True # equivalent to '(),()->()' 4574 )�reducea� 4575 reduce(array, axis=0, dtype=None, out=None, keepdims=False, initial=<no value>, where=True) 4576 4577 Reduces `array`'s dimension by one, by applying ufunc along one axis. 4578 4579 Let :math:`array.shape = (N_0, ..., N_i, ..., N_{M-1})`. Then 4580 :math:`ufunc.reduce(array, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}]` = 4581 the result of iterating `j` over :math:`range(N_i)`, cumulatively applying 4582 ufunc to each :math:`array[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]`. 4583 For a one-dimensional array, reduce produces results equivalent to: 4584 :: 4585 4586 r = op.identity # op = ufunc 4587 for i in range(len(A)): 4588 r = op(r, A[i]) 4589 return r 4590 4591 For example, add.reduce() is equivalent to sum(). 4592 4593 Parameters 4594 ---------- 4595 array : array_like 4596 The array to act on. 4597 axis : None or int or tuple of ints, optional 4598 Axis or axes along which a reduction is performed. 4599 The default (`axis` = 0) is perform a reduction over the first 4600 dimension of the input array. `axis` may be negative, in 4601 which case it counts from the last to the first axis. 4602 4603 .. versionadded:: 1.7.0 4604 4605 If this is None, a reduction is performed over all the axes. 4606 If this is a tuple of ints, a reduction is performed on multiple 4607 axes, instead of a single axis or all the axes as before. 4608 4609 For operations which are either not commutative or not associative, 4610 doing a reduction over multiple axes is not well-defined. The 4611 ufuncs do not currently raise an exception in this case, but will 4612 likely do so in the future. 4613 dtype : data-type code, optional 4614 The type used to represent the intermediate results. Defaults 4615 to the data-type of the output array if this is provided, or 4616 the data-type of the input array if no output array is provided. 4617 out : ndarray, None, or tuple of ndarray and None, optional 4618 A location into which the result is stored. If not provided or None, 4619 a freshly-allocated array is returned. For consistency with 4620 ``ufunc.__call__``, if given as a keyword, this may be wrapped in a 4621 1-element tuple. 4622 4623 .. versionchanged:: 1.13.0 4624 Tuples are allowed for keyword argument. 4625 keepdims : bool, optional 4626 If this is set to True, the axes which are reduced are left 4627 in the result as dimensions with size one. With this option, 4628 the result will broadcast correctly against the original `array`. 4629 4630 .. versionadded:: 1.7.0 4631 initial : scalar, optional 4632 The value with which to start the reduction. 4633 If the ufunc has no identity or the dtype is object, this defaults 4634 to None - otherwise it defaults to ufunc.identity. 4635 If ``None`` is given, the first element of the reduction is used, 4636 and an error is thrown if the reduction is empty. 4637 4638 .. versionadded:: 1.15.0 4639 4640 where : array_like of bool, optional 4641 A boolean array which is broadcasted to match the dimensions 4642 of `array`, and selects elements to include in the reduction. Note 4643 that for ufuncs like ``minimum`` that do not have an identity 4644 defined, one has to pass in also ``initial``. 4645 4646 .. versionadded:: 1.17.0 4647 4648 Returns 4649 ------- 4650 r : ndarray 4651 The reduced array. If `out` was supplied, `r` is a reference to it. 4652 4653 Examples 4654 -------- 4655 >>> np.multiply.reduce([2,3,5]) 4656 30 4657 4658 A multi-dimensional array example: 4659 4660 >>> X = np.arange(8).reshape((2,2,2)) 4661 >>> X 4662 array([[[0, 1], 4663 [2, 3]], 4664 [[4, 5], 4665 [6, 7]]]) 4666 >>> np.add.reduce(X, 0) 4667 array([[ 4, 6], 4668 [ 8, 10]]) 4669 >>> np.add.reduce(X) # confirm: default axis value is 0 4670 array([[ 4, 6], 4671 [ 8, 10]]) 4672 >>> np.add.reduce(X, 1) 4673 array([[ 2, 4], 4674 [10, 12]]) 4675 >>> np.add.reduce(X, 2) 4676 array([[ 1, 5], 4677 [ 9, 13]]) 4678 4679 You can use the ``initial`` keyword argument to initialize the reduction 4680 with a different value, and ``where`` to select specific elements to include: 4681 4682 >>> np.add.reduce([10], initial=5) 4683 15 4684 >>> np.add.reduce(np.ones((2, 2, 2)), axis=(0, 2), initial=10) 4685 array([14., 14.]) 4686 >>> a = np.array([10., np.nan, 10]) 4687 >>> np.add.reduce(a, where=~np.isnan(a)) 4688 20.0 4689 4690 Allows reductions of empty arrays where they would normally fail, i.e. 4691 for ufuncs without an identity. 4692 4693 >>> np.minimum.reduce([], initial=np.inf) 4694 inf 4695 >>> np.minimum.reduce([[1., 2.], [3., 4.]], initial=10., where=[True, False]) 4696 array([ 1., 10.]) 4697 >>> np.minimum.reduce([]) 4698 Traceback (most recent call last): 4699 ... 4700 ValueError: zero-size array to reduction operation minimum which has no identity 4701 )� 4702 accumulatea� 4703 accumulate(array, axis=0, dtype=None, out=None) 4704 4705 Accumulate the result of applying the operator to all elements. 4706 4707 For a one-dimensional array, accumulate produces results equivalent to:: 4708 4709 r = np.empty(len(A)) 4710 t = op.identity # op = the ufunc being applied to A's elements 4711 for i in range(len(A)): 4712 t = op(t, A[i]) 4713 r[i] = t 4714 return r 4715 4716 For example, add.accumulate() is equivalent to np.cumsum(). 4717 4718 For a multi-dimensional array, accumulate is applied along only one 4719 axis (axis zero by default; see Examples below) so repeated use is 4720 necessary if one wants to accumulate over multiple axes. 4721 4722 Parameters 4723 ---------- 4724 array : array_like 4725 The array to act on. 4726 axis : int, optional 4727 The axis along which to apply the accumulation; default is zero. 4728 dtype : data-type code, optional 4729 The data-type used to represent the intermediate results. Defaults 4730 to the data-type of the output array if such is provided, or the 4731 data-type of the input array if no output array is provided. 4732 out : ndarray, None, or tuple of ndarray and None, optional 4733 A location into which the result is stored. If not provided or None, 4734 a freshly-allocated array is returned. For consistency with 4735 ``ufunc.__call__``, if given as a keyword, this may be wrapped in a 4736 1-element tuple. 4737 4738 .. versionchanged:: 1.13.0 4739 Tuples are allowed for keyword argument. 4740 4741 Returns 4742 ------- 4743 r : ndarray 4744 The accumulated values. If `out` was supplied, `r` is a reference to 4745 `out`. 4746 4747 Examples 4748 -------- 4749 1-D array examples: 4750 4751 >>> np.add.accumulate([2, 3, 5]) 4752 array([ 2, 5, 10]) 4753 >>> np.multiply.accumulate([2, 3, 5]) 4754 array([ 2, 6, 30]) 4755 4756 2-D array examples: 4757 4758 >>> I = np.eye(2) 4759 >>> I 4760 array([[1., 0.], 4761 [0., 1.]]) 4762 4763 Accumulate along axis 0 (rows), down columns: 4764 4765 >>> np.add.accumulate(I, 0) 4766 array([[1., 0.], 4767 [1., 1.]]) 4768 >>> np.add.accumulate(I) # no axis specified = axis zero 4769 array([[1., 0.], 4770 [1., 1.]]) 4771 4772 Accumulate along axis 1 (columns), through rows: 4773 4774 >>> np.add.accumulate(I, 1) 4775 array([[1., 1.], 4776 [0., 1.]]) 4777 4778 )�reduceata� 4779 reduceat(array, indices, axis=0, dtype=None, out=None) 4780 4781 Performs a (local) reduce with specified slices over a single axis. 4782 4783 For i in ``range(len(indices))``, `reduceat` computes 4784 ``ufunc.reduce(array[indices[i]:indices[i+1]])``, which becomes the i-th 4785 generalized "row" parallel to `axis` in the final result (i.e., in a 4786 2-D array, for example, if `axis = 0`, it becomes the i-th row, but if 4787 `axis = 1`, it becomes the i-th column). There are three exceptions to this: 4788 4789 * when ``i = len(indices) - 1`` (so for the last index), 4790 ``indices[i+1] = array.shape[axis]``. 4791 * if ``indices[i] >= indices[i + 1]``, the i-th generalized "row" is 4792 simply ``array[indices[i]]``. 4793 * if ``indices[i] >= len(array)`` or ``indices[i] < 0``, an error is raised. 4794 4795 The shape of the output depends on the size of `indices`, and may be 4796 larger than `array` (this happens if ``len(indices) > array.shape[axis]``). 4797 4798 Parameters 4799 ---------- 4800 array : array_like 4801 The array to act on. 4802 indices : array_like 4803 Paired indices, comma separated (not colon), specifying slices to 4804 reduce. 4805 axis : int, optional 4806 The axis along which to apply the reduceat. 4807 dtype : data-type code, optional 4808 The type used to represent the intermediate results. Defaults 4809 to the data type of the output array if this is provided, or 4810 the data type of the input array if no output array is provided. 4811 out : ndarray, None, or tuple of ndarray and None, optional 4812 A location into which the result is stored. If not provided or None, 4813 a freshly-allocated array is returned. For consistency with 4814 ``ufunc.__call__``, if given as a keyword, this may be wrapped in a 4815 1-element tuple. 4816 4817 .. versionchanged:: 1.13.0 4818 Tuples are allowed for keyword argument. 4819 4820 Returns 4821 ------- 4822 r : ndarray 4823 The reduced values. If `out` was supplied, `r` is a reference to 4824 `out`. 4825 4826 Notes 4827 ----- 4828 A descriptive example: 4829 4830 If `array` is 1-D, the function `ufunc.accumulate(array)` is the same as 4831 ``ufunc.reduceat(array, indices)[::2]`` where `indices` is 4832 ``range(len(array) - 1)`` with a zero placed 4833 in every other element: 4834 ``indices = zeros(2 * len(array) - 1)``, 4835 ``indices[1::2] = range(1, len(array))``. 4836 4837 Don't be fooled by this attribute's name: `reduceat(array)` is not 4838 necessarily smaller than `array`. 4839 4840 Examples 4841 -------- 4842 To take the running sum of four successive values: 4843 4844 >>> np.add.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2] 4845 array([ 6, 10, 14, 18]) 4846 4847 A 2-D example: 4848 4849 >>> x = np.linspace(0, 15, 16).reshape(4,4) 4850 >>> x 4851 array([[ 0., 1., 2., 3.], 4852 [ 4., 5., 6., 7.], 4853 [ 8., 9., 10., 11.], 4854 [12., 13., 14., 15.]]) 4855 4856 :: 4857 4858 # reduce such that the result has the following five rows: 4859 # [row1 + row2 + row3] 4860 # [row4] 4861 # [row2] 4862 # [row3] 4863 # [row1 + row2 + row3 + row4] 4864 4865 >>> np.add.reduceat(x, [0, 3, 1, 2, 0]) 4866 array([[12., 15., 18., 21.], 4867 [12., 13., 14., 15.], 4868 [ 4., 5., 6., 7.], 4869 [ 8., 9., 10., 11.], 4870 [24., 28., 32., 36.]]) 4871 4872 :: 4873 4874 # reduce such that result has the following two columns: 4875 # [col1 * col2 * col3, col4] 4876 4877 >>> np.multiply.reduceat(x, [0, 3], 1) 4878 array([[ 0., 3.], 4879 [ 120., 7.], 4880 [ 720., 11.], 4881 [2184., 15.]]) 4882 4883 )�outeraX 4884 outer(A, B, /, **kwargs) 4885 4886 Apply the ufunc `op` to all pairs (a, b) with a in `A` and b in `B`. 4887 4888 Let ``M = A.ndim``, ``N = B.ndim``. Then the result, `C`, of 4889 ``op.outer(A, B)`` is an array of dimension M + N such that: 4890 4891 .. math:: C[i_0, ..., i_{M-1}, j_0, ..., j_{N-1}] = 4892 op(A[i_0, ..., i_{M-1}], B[j_0, ..., j_{N-1}]) 4893 4894 For `A` and `B` one-dimensional, this is equivalent to:: 4895 4896 r = empty(len(A),len(B)) 4897 for i in range(len(A)): 4898 for j in range(len(B)): 4899 r[i,j] = op(A[i], B[j]) # op = ufunc in question 4900 4901 Parameters 4902 ---------- 4903 A : array_like 4904 First array 4905 B : array_like 4906 Second array 4907 kwargs : any 4908 Arguments to pass on to the ufunc. Typically `dtype` or `out`. 4909 See `ufunc` for a comprehensive overview of all available arguments. 4910 4911 Returns 4912 ------- 4913 r : ndarray 4914 Output array 4915 4916 See Also 4917 -------- 4918 numpy.outer : A less powerful version of ``np.multiply.outer`` 4919 that `ravel`\ s all inputs to 1D. This exists 4920 primarily for compatibility with old code. 4921 4922 tensordot : ``np.tensordot(a, b, axes=((), ()))`` and 4923 ``np.multiply.outer(a, b)`` behave same for all 4924 dimensions of a and b. 4925 4926 Examples 4927 -------- 4928 >>> np.multiply.outer([1, 2, 3], [4, 5, 6]) 4929 array([[ 4, 5, 6], 4930 [ 8, 10, 12], 4931 [12, 15, 18]]) 4932 4933 A multi-dimensional example: 4934 4935 >>> A = np.array([[1, 2, 3], [4, 5, 6]]) 4936 >>> A.shape 4937 (2, 3) 4938 >>> B = np.array([[1, 2, 3, 4]]) 4939 >>> B.shape 4940 (1, 4) 4941 >>> C = np.multiply.outer(A, B) 4942 >>> C.shape; C 4943 (2, 3, 1, 4) 4944 array([[[[ 1, 2, 3, 4]], 4945 [[ 2, 4, 6, 8]], 4946 [[ 3, 6, 9, 12]]], 4947 [[[ 4, 8, 12, 16]], 4948 [[ 5, 10, 15, 20]], 4949 [[ 6, 12, 18, 24]]]]) 4950 4951 )�ata+ 4952 at(a, indices, b=None, /) 4953 4954 Performs unbuffered in place operation on operand 'a' for elements 4955 specified by 'indices'. For addition ufunc, this method is equivalent to 4956 ``a[indices] += b``, except that results are accumulated for elements that 4957 are indexed more than once. For example, ``a[[0,0]] += 1`` will only 4958 increment the first element once because of buffering, whereas 4959 ``add.at(a, [0,0], 1)`` will increment the first element twice. 4960 4961 .. versionadded:: 1.8.0 4962 4963 Parameters 4964 ---------- 4965 a : array_like 4966 The array to perform in place operation on. 4967 indices : array_like or tuple 4968 Array like index object or slice object for indexing into first 4969 operand. If first operand has multiple dimensions, indices can be a 4970 tuple of array like index objects or slice objects. 4971 b : array_like 4972 Second operand for ufuncs requiring two operands. Operand must be 4973 broadcastable over first operand after indexing or slicing. 4974 4975 Examples 4976 -------- 4977 Set items 0 and 1 to their negative values: 4978 4979 >>> a = np.array([1, 2, 3, 4]) 4980 >>> np.negative.at(a, [0, 1]) 4981 >>> a 4982 array([-1, -2, 3, 4]) 4983 4984 Increment items 0 and 1, and increment item 2 twice: 4985 4986 >>> a = np.array([1, 2, 3, 4]) 4987 >>> np.add.at(a, [0, 1, 2, 2], 1) 4988 >>> a 4989 array([2, 3, 5, 4]) 4990 4991 Add items 0 and 1 in first array to second array, 4992 and store results in first array: 4993 4994 >>> a = np.array([1, 2, 3, 4]) 4995 >>> b = np.array([1, 2]) 4996 >>> np.add.at(a, [0, 1], b) 4997 >>> a 4998 array([2, 4, 3, 4]) 4999 5000 )�resolve_dtypesa> 5001 resolve_dtypes(dtypes, *, signature=None, casting=None, reduction=False) 5002 5003 Find the dtypes NumPy will use for the operation. Both input and 5004 output dtypes are returned and may differ from those provided. 5005 5006 .. note:: 5007 5008 This function always applies NEP 50 rules since it is not provided 5009 any actual values. The Python types ``int``, ``float``, and 5010 ``complex`` thus behave weak and should be passed for "untyped" 5011 Python input. 5012 5013 Parameters 5014 ---------- 5015 dtypes : tuple of dtypes, None, or literal int, float, complex 5016 The input dtypes for each operand. Output operands can be 5017 None, indicating that the dtype must be found. 5018 signature : tuple of DTypes or None, optional 5019 If given, enforces exact DType (classes) of the specific operand. 5020 The ufunc ``dtype`` argument is equivalent to passing a tuple with 5021 only output dtypes set. 5022 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional 5023 The casting mode when casting is necessary. This is identical to 5024 the ufunc call casting modes. 5025 reduction : boolean 5026 If given, the resolution assumes a reduce operation is happening 5027 which slightly changes the promotion and type resolution rules. 5028 `dtypes` is usually something like ``(None, np.dtype("i2"), None)`` 5029 for reductions (first input is also the output). 5030 5031 .. note:: 5032 5033 The default casting mode is "same_kind", however, as of 5034 NumPy 1.24, NumPy uses "unsafe" for reductions. 5035 5036 Returns 5037 ------- 5038 dtypes : tuple of dtypes 5039 The dtypes which NumPy would use for the calculation. Note that 5040 dtypes may not match the passed in ones (casting is necessary). 5041 5042 See Also 5043 -------- 5044 numpy.ufunc._resolve_dtypes_and_context : 5045 Similar function to this, but returns additional information which 5046 give access to the core C functionality of NumPy. 5047 5048 Examples 5049 -------- 5050 This API requires passing dtypes, define them for convenience: 5051 5052 >>> int32 = np.dtype("int32") 5053 >>> float32 = np.dtype("float32") 5054 5055 The typical ufunc call does not pass an output dtype. `np.add` has two 5056 inputs and one output, so leave the output as ``None`` (not provided): 5057 5058 >>> np.add.resolve_dtypes((int32, float32, None)) 5059 (dtype('float64'), dtype('float64'), dtype('float64')) 5060 5061 The loop found uses "float64" for all operands (including the output), the 5062 first input would be cast. 5063 5064 ``resolve_dtypes`` supports "weak" handling for Python scalars by passing 5065 ``int``, ``float``, or ``complex``: 5066 5067 >>> np.add.resolve_dtypes((float32, float, None)) 5068 (dtype('float32'), dtype('float32'), dtype('float32')) 5069 5070 Where the Python ``float`` behaves samilar to a Python value ``0.0`` 5071 in a ufunc call. (See :ref:`NEP 50 <NEP50>` for details.) 5072 5073 )�_resolve_dtypes_and_contextaF 5074 _resolve_dtypes_and_context(dtypes, *, signature=None, casting=None, reduction=False) 5075 5076 See `numpy.ufunc.resolve_dtypes` for parameter information. This 5077 function is considered *unstable*. You may use it, but the returned 5078 information is NumPy version specific and expected to change. 5079 Large API/ABI changes are not expected, but a new NumPy version is 5080 expected to require updating code using this functionality. 5081 5082 This function is designed to be used in conjunction with 5083 `numpy.ufunc._get_strided_loop`. The calls are split to mirror the C API 5084 and allow future improvements. 5085 5086 Returns 5087 ------- 5088 dtypes : tuple of dtypes 5089 call_info : 5090 PyCapsule with all necessary information to get access to low level 5091 C calls. See `numpy.ufunc._get_strided_loop` for more information. 5092 5093 )�_get_strided_loopa� 5094 _get_strided_loop(call_info, /, *, fixed_strides=None) 5095 5096 This function fills in the ``call_info`` capsule to include all 5097 information necessary to call the low-level strided loop from NumPy. 5098 5099 See notes for more information. 5100 5101 Parameters 5102 ---------- 5103 call_info : PyCapsule 5104 The PyCapsule returned by `numpy.ufunc._resolve_dtypes_and_context`. 5105 fixed_strides : tuple of int or None, optional 5106 A tuple with fixed byte strides of all input arrays. NumPy may use 5107 this information to find specialized loops, so any call must follow 5108 the given stride. Use ``None`` to indicate that the stride is not 5109 known (or not fixed) for all calls. 5110 5111 Notes 5112 ----- 5113 Together with `numpy.ufunc._resolve_dtypes_and_context` this function 5114 gives low-level access to the NumPy ufunc loops. 5115 The first function does general preparation and returns the required 5116 information. It returns this as a C capsule with the version specific 5117 name ``numpy_1.24_ufunc_call_info``. 5118 The NumPy 1.24 ufunc call info capsule has the following layout:: 5119 5120 typedef struct { 5121 PyArrayMethod_StridedLoop *strided_loop; 5122 PyArrayMethod_Context *context; 5123 NpyAuxData *auxdata; 5124 5125 /* Flag information (expected to change) */ 5126 npy_bool requires_pyapi; /* GIL is required by loop */ 5127 5128 /* Loop doesn't set FPE flags; if not set check FPE flags */ 5129 npy_bool no_floatingpoint_errors; 5130 } ufunc_call_info; 5131 5132 Note that the first call only fills in the ``context``. The call to 5133 ``_get_strided_loop`` fills in all other data. 5134 Please see the ``numpy/experimental_dtype_api.h`` header for exact 5135 call information; the main thing to note is that the new-style loops 5136 return 0 on success, -1 on failure. They are passed context as new 5137 first input and ``auxdata`` as (replaced) last. 5138 5139 Only the ``strided_loop``signature is considered guaranteed stable 5140 for NumPy bug-fix releases. All other API is tied to the experimental 5141 API versioning. 5142 5143 The reason for the split call is that cast information is required to 5144 decide what the fixed-strides will be. 5145 5146 NumPy ties the lifetime of the ``auxdata`` information to the capsule. 5147 5148 r; a� 5149 dtype(dtype, align=False, copy=False) 5150 5151 Create a data type object. 5152 5153 A numpy array is homogeneous, and contains elements described by a 5154 dtype object. A dtype object can be constructed from different 5155 combinations of fundamental numeric types. 5156 5157 Parameters 5158 ---------- 5159 dtype 5160 Object to be converted to a data type object. 5161 align : bool, optional 5162 Add padding to the fields to match what a C compiler would output 5163 for a similar C-struct. Can be ``True`` only if `obj` is a dictionary 5164 or a comma-separated string. If a struct dtype is being created, 5165 this also sets a sticky alignment flag ``isalignedstruct``. 5166 copy : bool, optional 5167 Make a new copy of the data-type object. If ``False``, the result 5168 may just be a reference to a built-in data-type object. 5169 5170 See also 5171 -------- 5172 result_type 5173 5174 Examples 5175 -------- 5176 Using array-scalar type: 5177 5178 >>> np.dtype(np.int16) 5179 dtype('int16') 5180 5181 Structured type, one field name 'f1', containing int16: 5182 5183 >>> np.dtype([('f1', np.int16)]) 5184 dtype([('f1', '<i2')]) 5185 5186 Structured type, one field named 'f1', in itself containing a structured 5187 type with one field: 5188 5189 >>> np.dtype([('f1', [('f1', np.int16)])]) 5190 dtype([('f1', [('f1', '<i2')])]) 5191 5192 Structured type, two fields: the first field contains an unsigned int, the 5193 second an int32: 5194 5195 >>> np.dtype([('f1', np.uint64), ('f2', np.int32)]) 5196 dtype([('f1', '<u8'), ('f2', '<i4')]) 5197 5198 Using array-protocol type strings: 5199 5200 >>> np.dtype([('a','f8'),('b','S10')]) 5201 dtype([('a', '<f8'), ('b', 'S10')]) 5202 5203 Using comma-separated field formats. The shape is (2,3): 5204 5205 >>> np.dtype("i4, (2,3)f8") 5206 dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))]) 5207 5208 Using tuples. ``int`` is a fixed type, 3 the field's shape. ``void`` 5209 is a flexible type, here of size 10: 5210 5211 >>> np.dtype([('hello',(np.int64,3)),('world',np.void,10)]) 5212 dtype([('hello', '<i8', (3,)), ('world', 'V10')]) 5213 5214 Subdivide ``int16`` into 2 ``int8``'s, called x and y. 0 and 1 are 5215 the offsets in bytes: 5216 5217 >>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)})) 5218 dtype((numpy.int16, [('x', 'i1'), ('y', 'i1')])) 5219 5220 Using dictionaries. Two fields named 'gender' and 'age': 5221 5222 >>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]}) 5223 dtype([('gender', 'S1'), ('age', 'u1')]) 5224 5225 Offsets in bytes, here 0 and 25: 5226 5227 >>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)}) 5228 dtype([('surname', 'S25'), ('age', 'u1')]) 5229 5230 )� alignmenta% 5231 The required alignment (bytes) of this data-type according to the compiler. 5232 5233 More information is available in the C-API section of the manual. 5234 5235 Examples 5236 -------- 5237 5238 >>> x = np.dtype('i4') 5239 >>> x.alignment 5240 4 5241 5242 >>> x = np.dtype(float) 5243 >>> x.alignment 5244 8 5245 5246 )� byteordera� 5247 A character indicating the byte-order of this data-type object. 5248 5249 One of: 5250 5251 === ============== 5252 '=' native 5253 '<' little-endian 5254 '>' big-endian 5255 '|' not applicable 5256 === ============== 5257 5258 All built-in data-type objects have byteorder either '=' or '|'. 5259 5260 Examples 5261 -------- 5262 5263 >>> dt = np.dtype('i2') 5264 >>> dt.byteorder 5265 '=' 5266 >>> # endian is not relevant for 8 bit numbers 5267 >>> np.dtype('i1').byteorder 5268 '|' 5269 >>> # or ASCII strings 5270 >>> np.dtype('S2').byteorder 5271 '|' 5272 >>> # Even if specific code is given, and it is native 5273 >>> # '=' is the byteorder 5274 >>> import sys 5275 >>> sys_is_le = sys.byteorder == 'little' 5276 >>> native_code = sys_is_le and '<' or '>' 5277 >>> swapped_code = sys_is_le and '>' or '<' 5278 >>> dt = np.dtype(native_code + 'i2') 5279 >>> dt.byteorder 5280 '=' 5281 >>> # Swapped code shows up as itself 5282 >>> dt = np.dtype(swapped_code + 'i2') 5283 >>> dt.byteorder == swapped_code 5284 True 5285 5286 )�charz�A unique character code for each of the 21 different built-in types. 5287 5288 Examples 5289 -------- 5290 5291 >>> x = np.dtype(float) 5292 >>> x.char 5293 'd' 5294 5295 )�descraQ 5296 `__array_interface__` description of the data-type. 5297 5298 The format is that required by the 'descr' key in the 5299 `__array_interface__` attribute. 5300 5301 Warning: This attribute exists specifically for `__array_interface__`, 5302 and passing it directly to `np.dtype` will not accurately reconstruct 5303 some dtypes (e.g., scalar and subarray dtypes). 5304 5305 Examples 5306 -------- 5307 5308 >>> x = np.dtype(float) 5309 >>> x.descr 5310 [('', '<f8')] 5311 5312 >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) 5313 >>> dt.descr 5314 [('name', '<U16'), ('grades', '<f8', (2,))] 5315 5316 )�fieldsa� 5317 Dictionary of named fields defined for this data type, or ``None``. 5318 5319 The dictionary is indexed by keys that are the names of the fields. 5320 Each entry in the dictionary is a tuple fully describing the field:: 5321 5322 (dtype, offset[, title]) 5323 5324 Offset is limited to C int, which is signed and usually 32 bits. 5325 If present, the optional title can be any object (if it is a string 5326 or unicode then it will also be a key in the fields dictionary, 5327 otherwise it's meta-data). Notice also that the first two elements 5328 of the tuple can be passed directly as arguments to the ``ndarray.getfield`` 5329 and ``ndarray.setfield`` methods. 5330 5331 See Also 5332 -------- 5333 ndarray.getfield, ndarray.setfield 5334 5335 Examples 5336 -------- 5337 >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) 5338 >>> print(dt.fields) 5339 {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)} 5340 5341 )r>