Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/numpy/_core/_add_newdocs.py: 100%

272 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2024-04-09 06:12 +0000

1""" 

2This is only meant to add docs to objects defined in C-extension modules. 

3The purpose is to allow easier editing of the docstrings without 

4requiring a re-compile. 

5 

6NOTE: Many of the methods of ndarray have corresponding functions. 

7 If you update these docstrings, please keep also the ones in 

8 _core/fromnumeric.py, matrixlib/defmatrix.py up-to-date. 

9 

10""" 

11 

12from numpy._core.function_base import add_newdoc 

13from numpy._core.overrides import array_function_like_doc 

14 

15 

16############################################################################### 

17# 

18# flatiter 

19# 

20# flatiter needs a toplevel description 

21# 

22############################################################################### 

23 

24add_newdoc('numpy._core', 'flatiter', 

25 """ 

26 Flat iterator object to iterate over arrays. 

27 

28 A `flatiter` iterator is returned by ``x.flat`` for any array `x`. 

29 It allows iterating over the array as if it were a 1-D array, 

30 either in a for-loop or by calling its `next` method. 

31 

32 Iteration is done in row-major, C-style order (the last 

33 index varying the fastest). The iterator can also be indexed using 

34 basic slicing or advanced indexing. 

35 

36 See Also 

37 -------- 

38 ndarray.flat : Return a flat iterator over an array. 

39 ndarray.flatten : Returns a flattened copy of an array. 

40 

41 Notes 

42 ----- 

43 A `flatiter` iterator can not be constructed directly from Python code 

44 by calling the `flatiter` constructor. 

45 

46 Examples 

47 -------- 

48 >>> x = np.arange(6).reshape(2, 3) 

49 >>> fl = x.flat 

50 >>> type(fl) 

51 <class 'numpy.flatiter'> 

52 >>> for item in fl: 

53 ... print(item) 

54 ... 

55 0 

56 1 

57 2 

58 3 

59 4 

60 5 

61 

62 >>> fl[2:4] 

63 array([2, 3]) 

64 

65 """) 

66 

67# flatiter attributes 

68 

69add_newdoc('numpy._core', 'flatiter', ('base', 

70 """ 

71 A reference to the array that is iterated over. 

72 

73 Examples 

74 -------- 

75 >>> x = np.arange(5) 

76 >>> fl = x.flat 

77 >>> fl.base is x 

78 True 

79 

80 """)) 

81 

82 

83add_newdoc('numpy._core', 'flatiter', ('coords', 

84 """ 

85 An N-dimensional tuple of current coordinates. 

86 

87 Examples 

88 -------- 

89 >>> x = np.arange(6).reshape(2, 3) 

90 >>> fl = x.flat 

91 >>> fl.coords 

92 (0, 0) 

93 >>> next(fl) 

94 0 

95 >>> fl.coords 

96 (0, 1) 

97 

98 """)) 

99 

100 

101add_newdoc('numpy._core', 'flatiter', ('index', 

102 """ 

103 Current flat index into the array. 

104 

105 Examples 

106 -------- 

107 >>> x = np.arange(6).reshape(2, 3) 

108 >>> fl = x.flat 

109 >>> fl.index 

110 0 

111 >>> next(fl) 

112 0 

113 >>> fl.index 

114 1 

115 

116 """)) 

117 

118# flatiter functions 

119 

120add_newdoc('numpy._core', 'flatiter', ('__array__', 

121 """__array__(type=None) Get array from iterator 

122 

123 """)) 

124 

125 

126add_newdoc('numpy._core', 'flatiter', ('copy', 

127 """ 

128 copy() 

129 

130 Get a copy of the iterator as a 1-D array. 

131 

132 Examples 

133 -------- 

134 >>> x = np.arange(6).reshape(2, 3) 

135 >>> x 

136 array([[0, 1, 2], 

137 [3, 4, 5]]) 

138 >>> fl = x.flat 

139 >>> fl.copy() 

140 array([0, 1, 2, 3, 4, 5]) 

141 

142 """)) 

143 

144 

145############################################################################### 

146# 

147# nditer 

148# 

149############################################################################### 

150 

151add_newdoc('numpy._core', 'nditer', 

152 """ 

153 nditer(op, flags=None, op_flags=None, op_dtypes=None, order='K', 

154 casting='safe', op_axes=None, itershape=None, buffersize=0) 

155 

156 Efficient multi-dimensional iterator object to iterate over arrays. 

157 To get started using this object, see the 

158 :ref:`introductory guide to array iteration <arrays.nditer>`. 

159 

160 Parameters 

161 ---------- 

162 op : ndarray or sequence of array_like 

163 The array(s) to iterate over. 

164 

165 flags : sequence of str, optional 

166 Flags to control the behavior of the iterator. 

167 

168 * ``buffered`` enables buffering when required. 

169 * ``c_index`` causes a C-order index to be tracked. 

170 * ``f_index`` causes a Fortran-order index to be tracked. 

171 * ``multi_index`` causes a multi-index, or a tuple of indices 

172 with one per iteration dimension, to be tracked. 

173 * ``common_dtype`` causes all the operands to be converted to 

174 a common data type, with copying or buffering as necessary. 

175 * ``copy_if_overlap`` causes the iterator to determine if read 

176 operands have overlap with write operands, and make temporary 

177 copies as necessary to avoid overlap. False positives (needless 

178 copying) are possible in some cases. 

179 * ``delay_bufalloc`` delays allocation of the buffers until 

180 a reset() call is made. Allows ``allocate`` operands to 

181 be initialized before their values are copied into the buffers. 

182 * ``external_loop`` causes the ``values`` given to be 

183 one-dimensional arrays with multiple values instead of 

184 zero-dimensional arrays. 

185 * ``grow_inner`` allows the ``value`` array sizes to be made 

186 larger than the buffer size when both ``buffered`` and 

187 ``external_loop`` is used. 

188 * ``ranged`` allows the iterator to be restricted to a sub-range 

189 of the iterindex values. 

190 * ``refs_ok`` enables iteration of reference types, such as 

191 object arrays. 

192 * ``reduce_ok`` enables iteration of ``readwrite`` operands 

193 which are broadcasted, also known as reduction operands. 

194 * ``zerosize_ok`` allows `itersize` to be zero. 

195 op_flags : list of list of str, optional 

196 This is a list of flags for each operand. At minimum, one of 

197 ``readonly``, ``readwrite``, or ``writeonly`` must be specified. 

198 

199 * ``readonly`` indicates the operand will only be read from. 

200 * ``readwrite`` indicates the operand will be read from and written to. 

201 * ``writeonly`` indicates the operand will only be written to. 

202 * ``no_broadcast`` prevents the operand from being broadcasted. 

203 * ``contig`` forces the operand data to be contiguous. 

204 * ``aligned`` forces the operand data to be aligned. 

205 * ``nbo`` forces the operand data to be in native byte order. 

206 * ``copy`` allows a temporary read-only copy if required. 

207 * ``updateifcopy`` allows a temporary read-write copy if required. 

208 * ``allocate`` causes the array to be allocated if it is None 

209 in the ``op`` parameter. 

210 * ``no_subtype`` prevents an ``allocate`` operand from using a subtype. 

211 * ``arraymask`` indicates that this operand is the mask to use 

212 for selecting elements when writing to operands with the 

213 'writemasked' flag set. The iterator does not enforce this, 

214 but when writing from a buffer back to the array, it only 

215 copies those elements indicated by this mask. 

216 * ``writemasked`` indicates that only elements where the chosen 

217 ``arraymask`` operand is True will be written to. 

218 * ``overlap_assume_elementwise`` can be used to mark operands that are 

219 accessed only in the iterator order, to allow less conservative 

220 copying when ``copy_if_overlap`` is present. 

221 op_dtypes : dtype or tuple of dtype(s), optional 

222 The required data type(s) of the operands. If copying or buffering 

223 is enabled, the data will be converted to/from their original types. 

224 order : {'C', 'F', 'A', 'K'}, optional 

225 Controls the iteration order. 'C' means C order, 'F' means 

226 Fortran order, 'A' means 'F' order if all the arrays are Fortran 

227 contiguous, 'C' order otherwise, and 'K' means as close to the 

228 order the array elements appear in memory as possible. This also 

229 affects the element memory order of ``allocate`` operands, as they 

230 are allocated to be compatible with iteration order. 

231 Default is 'K'. 

232 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional 

233 Controls what kind of data casting may occur when making a copy 

234 or buffering. Setting this to 'unsafe' is not recommended, 

235 as it can adversely affect accumulations. 

236 

237 * 'no' means the data types should not be cast at all. 

238 * 'equiv' means only byte-order changes are allowed. 

239 * 'safe' means only casts which can preserve values are allowed. 

240 * 'same_kind' means only safe casts or casts within a kind, 

241 like float64 to float32, are allowed. 

242 * 'unsafe' means any data conversions may be done. 

243 op_axes : list of list of ints, optional 

244 If provided, is a list of ints or None for each operands. 

245 The list of axes for an operand is a mapping from the dimensions 

246 of the iterator to the dimensions of the operand. A value of 

247 -1 can be placed for entries, causing that dimension to be 

248 treated as `newaxis`. 

249 itershape : tuple of ints, optional 

250 The desired shape of the iterator. This allows ``allocate`` operands 

251 with a dimension mapped by op_axes not corresponding to a dimension 

252 of a different operand to get a value not equal to 1 for that 

253 dimension. 

254 buffersize : int, optional 

255 When buffering is enabled, controls the size of the temporary 

256 buffers. Set to 0 for the default value. 

257 

258 Attributes 

259 ---------- 

260 dtypes : tuple of dtype(s) 

261 The data types of the values provided in `value`. This may be 

262 different from the operand data types if buffering is enabled. 

263 Valid only before the iterator is closed. 

264 finished : bool 

265 Whether the iteration over the operands is finished or not. 

266 has_delayed_bufalloc : bool 

267 If True, the iterator was created with the ``delay_bufalloc`` flag, 

268 and no reset() function was called on it yet. 

269 has_index : bool 

270 If True, the iterator was created with either the ``c_index`` or 

271 the ``f_index`` flag, and the property `index` can be used to 

272 retrieve it. 

273 has_multi_index : bool 

274 If True, the iterator was created with the ``multi_index`` flag, 

275 and the property `multi_index` can be used to retrieve it. 

276 index 

277 When the ``c_index`` or ``f_index`` flag was used, this property 

278 provides access to the index. Raises a ValueError if accessed 

279 and ``has_index`` is False. 

280 iterationneedsapi : bool 

281 Whether iteration requires access to the Python API, for example 

282 if one of the operands is an object array. 

283 iterindex : int 

284 An index which matches the order of iteration. 

285 itersize : int 

286 Size of the iterator. 

287 itviews 

288 Structured view(s) of `operands` in memory, matching the reordered 

289 and optimized iterator access pattern. Valid only before the iterator 

290 is closed. 

291 multi_index 

292 When the ``multi_index`` flag was used, this property 

293 provides access to the index. Raises a ValueError if accessed 

294 accessed and ``has_multi_index`` is False. 

295 ndim : int 

296 The dimensions of the iterator. 

297 nop : int 

298 The number of iterator operands. 

299 operands : tuple of operand(s) 

300 The array(s) to be iterated over. Valid only before the iterator is 

301 closed. 

302 shape : tuple of ints 

303 Shape tuple, the shape of the iterator. 

304 value 

305 Value of ``operands`` at current iteration. Normally, this is a 

306 tuple of array scalars, but if the flag ``external_loop`` is used, 

307 it is a tuple of one dimensional arrays. 

308 

309 Notes 

310 ----- 

311 `nditer` supersedes `flatiter`. The iterator implementation behind 

312 `nditer` is also exposed by the NumPy C API. 

313 

314 The Python exposure supplies two iteration interfaces, one which follows 

315 the Python iterator protocol, and another which mirrors the C-style 

316 do-while pattern. The native Python approach is better in most cases, but 

317 if you need the coordinates or index of an iterator, use the C-style pattern. 

318 

319 Examples 

320 -------- 

321 Here is how we might write an ``iter_add`` function, using the 

322 Python iterator protocol: 

323 

324 >>> def iter_add_py(x, y, out=None): 

325 ... addop = np.add 

326 ... it = np.nditer([x, y, out], [], 

327 ... [['readonly'], ['readonly'], ['writeonly','allocate']]) 

328 ... with it: 

329 ... for (a, b, c) in it: 

330 ... addop(a, b, out=c) 

331 ... return it.operands[2] 

332 

333 Here is the same function, but following the C-style pattern: 

334 

335 >>> def iter_add(x, y, out=None): 

336 ... addop = np.add 

337 ... it = np.nditer([x, y, out], [], 

338 ... [['readonly'], ['readonly'], ['writeonly','allocate']]) 

339 ... with it: 

340 ... while not it.finished: 

341 ... addop(it[0], it[1], out=it[2]) 

342 ... it.iternext() 

343 ... return it.operands[2] 

344 

345 Here is an example outer product function: 

346 

347 >>> def outer_it(x, y, out=None): 

348 ... mulop = np.multiply 

349 ... it = np.nditer([x, y, out], ['external_loop'], 

350 ... [['readonly'], ['readonly'], ['writeonly', 'allocate']], 

351 ... op_axes=[list(range(x.ndim)) + [-1] * y.ndim, 

352 ... [-1] * x.ndim + list(range(y.ndim)), 

353 ... None]) 

354 ... with it: 

355 ... for (a, b, c) in it: 

356 ... mulop(a, b, out=c) 

357 ... return it.operands[2] 

358 

359 >>> a = np.arange(2)+1 

360 >>> b = np.arange(3)+1 

361 >>> outer_it(a,b) 

362 array([[1, 2, 3], 

363 [2, 4, 6]]) 

364 

365 Here is an example function which operates like a "lambda" ufunc: 

366 

367 >>> def luf(lamdaexpr, *args, **kwargs): 

368 ... '''luf(lambdaexpr, op1, ..., opn, out=None, order='K', casting='safe', buffersize=0)''' 

369 ... nargs = len(args) 

370 ... op = (kwargs.get('out',None),) + args 

371 ... it = np.nditer(op, ['buffered','external_loop'], 

372 ... [['writeonly','allocate','no_broadcast']] + 

373 ... [['readonly','nbo','aligned']]*nargs, 

374 ... order=kwargs.get('order','K'), 

375 ... casting=kwargs.get('casting','safe'), 

376 ... buffersize=kwargs.get('buffersize',0)) 

377 ... while not it.finished: 

378 ... it[0] = lamdaexpr(*it[1:]) 

379 ... it.iternext() 

380 ... return it.operands[0] 

381 

382 >>> a = np.arange(5) 

383 >>> b = np.ones(5) 

384 >>> luf(lambda i,j:i*i + j/2, a, b) 

385 array([ 0.5, 1.5, 4.5, 9.5, 16.5]) 

386 

387 If operand flags ``"writeonly"`` or ``"readwrite"`` are used the 

388 operands may be views into the original data with the 

389 `WRITEBACKIFCOPY` flag. In this case `nditer` must be used as a 

390 context manager or the `nditer.close` method must be called before 

391 using the result. The temporary data will be written back to the 

392 original data when the :meth:`~object.__exit__` function is called 

393 but not before: 

394 

395 >>> a = np.arange(6, dtype='i4')[::-2] 

396 >>> with np.nditer(a, [], 

397 ... [['writeonly', 'updateifcopy']], 

398 ... casting='unsafe', 

399 ... op_dtypes=[np.dtype('f4')]) as i: 

400 ... x = i.operands[0] 

401 ... x[:] = [-1, -2, -3] 

402 ... # a still unchanged here 

403 >>> a, x 

404 (array([-1, -2, -3], dtype=int32), array([-1., -2., -3.], dtype=float32)) 

405 

406 It is important to note that once the iterator is exited, dangling 

407 references (like `x` in the example) may or may not share data with 

408 the original data `a`. If writeback semantics were active, i.e. if 

409 `x.base.flags.writebackifcopy` is `True`, then exiting the iterator 

410 will sever the connection between `x` and `a`, writing to `x` will 

411 no longer write to `a`. If writeback semantics are not active, then 

412 `x.data` will still point at some part of `a.data`, and writing to 

413 one will affect the other. 

414 

415 Context management and the `close` method appeared in version 1.15.0. 

416 

417 """) 

418 

419# nditer methods 

420 

421add_newdoc('numpy._core', 'nditer', ('copy', 

422 """ 

423 copy() 

424 

425 Get a copy of the iterator in its current state. 

426 

427 Examples 

428 -------- 

429 >>> x = np.arange(10) 

430 >>> y = x + 1 

431 >>> it = np.nditer([x, y]) 

432 >>> next(it) 

433 (array(0), array(1)) 

434 >>> it2 = it.copy() 

435 >>> next(it2) 

436 (array(1), array(2)) 

437 

438 """)) 

439 

440add_newdoc('numpy._core', 'nditer', ('operands', 

441 """ 

442 operands[`Slice`] 

443 

444 The array(s) to be iterated over. Valid only before the iterator is closed. 

445 """)) 

446 

447add_newdoc('numpy._core', 'nditer', ('debug_print', 

448 """ 

449 debug_print() 

450 

451 Print the current state of the `nditer` instance and debug info to stdout. 

452 

453 """)) 

454 

455add_newdoc('numpy._core', 'nditer', ('enable_external_loop', 

456 """ 

457 enable_external_loop() 

458 

459 When the "external_loop" was not used during construction, but 

460 is desired, this modifies the iterator to behave as if the flag 

461 was specified. 

462 

463 """)) 

464 

465add_newdoc('numpy._core', 'nditer', ('iternext', 

466 """ 

467 iternext() 

468 

469 Check whether iterations are left, and perform a single internal iteration 

470 without returning the result. Used in the C-style pattern do-while 

471 pattern. For an example, see `nditer`. 

472 

473 Returns 

474 ------- 

475 iternext : bool 

476 Whether or not there are iterations left. 

477 

478 """)) 

479 

480add_newdoc('numpy._core', 'nditer', ('remove_axis', 

481 """ 

482 remove_axis(i, /) 

483 

484 Removes axis `i` from the iterator. Requires that the flag "multi_index" 

485 be enabled. 

486 

487 """)) 

488 

489add_newdoc('numpy._core', 'nditer', ('remove_multi_index', 

490 """ 

491 remove_multi_index() 

492 

493 When the "multi_index" flag was specified, this removes it, allowing 

494 the internal iteration structure to be optimized further. 

495 

496 """)) 

497 

498add_newdoc('numpy._core', 'nditer', ('reset', 

499 """ 

500 reset() 

501 

502 Reset the iterator to its initial state. 

503 

504 """)) 

505 

506add_newdoc('numpy._core', 'nested_iters', 

507 """ 

508 nested_iters(op, axes, flags=None, op_flags=None, op_dtypes=None, \ 

509 order="K", casting="safe", buffersize=0) 

510 

511 Create nditers for use in nested loops 

512 

513 Create a tuple of `nditer` objects which iterate in nested loops over 

514 different axes of the op argument. The first iterator is used in the 

515 outermost loop, the last in the innermost loop. Advancing one will change 

516 the subsequent iterators to point at its new element. 

517 

518 Parameters 

519 ---------- 

520 op : ndarray or sequence of array_like 

521 The array(s) to iterate over. 

522 

523 axes : list of list of int 

524 Each item is used as an "op_axes" argument to an nditer 

525 

526 flags, op_flags, op_dtypes, order, casting, buffersize (optional) 

527 See `nditer` parameters of the same name 

528 

529 Returns 

530 ------- 

531 iters : tuple of nditer 

532 An nditer for each item in `axes`, outermost first 

533 

534 See Also 

535 -------- 

536 nditer 

537 

538 Examples 

539 -------- 

540 

541 Basic usage. Note how y is the "flattened" version of 

542 [a[:, 0, :], a[:, 1, 0], a[:, 2, :]] since we specified 

543 the first iter's axes as [1] 

544 

545 >>> a = np.arange(12).reshape(2, 3, 2) 

546 >>> i, j = np.nested_iters(a, [[1], [0, 2]], flags=["multi_index"]) 

547 >>> for x in i: 

548 ... print(i.multi_index) 

549 ... for y in j: 

550 ... print('', j.multi_index, y) 

551 (0,) 

552 (0, 0) 0 

553 (0, 1) 1 

554 (1, 0) 6 

555 (1, 1) 7 

556 (1,) 

557 (0, 0) 2 

558 (0, 1) 3 

559 (1, 0) 8 

560 (1, 1) 9 

561 (2,) 

562 (0, 0) 4 

563 (0, 1) 5 

564 (1, 0) 10 

565 (1, 1) 11 

566 

567 """) 

568 

569add_newdoc('numpy._core', 'nditer', ('close', 

570 """ 

571 close() 

572 

573 Resolve all writeback semantics in writeable operands. 

574 

575 .. versionadded:: 1.15.0 

576 

577 See Also 

578 -------- 

579 

580 :ref:`nditer-context-manager` 

581 

582 """)) 

583 

584 

585############################################################################### 

586# 

587# broadcast 

588# 

589############################################################################### 

590 

591add_newdoc('numpy._core', 'broadcast', 

592 """ 

593 Produce an object that mimics broadcasting. 

594 

595 Parameters 

596 ---------- 

597 in1, in2, ... : array_like 

598 Input parameters. 

599 

600 Returns 

601 ------- 

602 b : broadcast object 

603 Broadcast the input parameters against one another, and 

604 return an object that encapsulates the result. 

605 Amongst others, it has ``shape`` and ``nd`` properties, and 

606 may be used as an iterator. 

607 

608 See Also 

609 -------- 

610 broadcast_arrays 

611 broadcast_to 

612 broadcast_shapes 

613 

614 Examples 

615 -------- 

616 

617 Manually adding two vectors, using broadcasting: 

618 

619 >>> x = np.array([[1], [2], [3]]) 

620 >>> y = np.array([4, 5, 6]) 

621 >>> b = np.broadcast(x, y) 

622 

623 >>> out = np.empty(b.shape) 

624 >>> out.flat = [u+v for (u,v) in b] 

625 >>> out 

626 array([[5., 6., 7.], 

627 [6., 7., 8.], 

628 [7., 8., 9.]]) 

629 

630 Compare against built-in broadcasting: 

631 

632 >>> x + y 

633 array([[5, 6, 7], 

634 [6, 7, 8], 

635 [7, 8, 9]]) 

636 

637 """) 

638 

639# attributes 

640 

641add_newdoc('numpy._core', 'broadcast', ('index', 

642 """ 

643 current index in broadcasted result 

644 

645 Examples 

646 -------- 

647 >>> x = np.array([[1], [2], [3]]) 

648 >>> y = np.array([4, 5, 6]) 

649 >>> b = np.broadcast(x, y) 

650 >>> b.index 

651 0 

652 >>> next(b), next(b), next(b) 

653 ((1, 4), (1, 5), (1, 6)) 

654 >>> b.index 

655 3 

656 

657 """)) 

658 

659add_newdoc('numpy._core', 'broadcast', ('iters', 

660 """ 

661 tuple of iterators along ``self``'s "components." 

662 

663 Returns a tuple of `numpy.flatiter` objects, one for each "component" 

664 of ``self``. 

665 

666 See Also 

667 -------- 

668 numpy.flatiter 

669 

670 Examples 

671 -------- 

672 >>> x = np.array([1, 2, 3]) 

673 >>> y = np.array([[4], [5], [6]]) 

674 >>> b = np.broadcast(x, y) 

675 >>> row, col = b.iters 

676 >>> next(row), next(col) 

677 (1, 4) 

678 

679 """)) 

680 

681add_newdoc('numpy._core', 'broadcast', ('ndim', 

682 """ 

683 Number of dimensions of broadcasted result. Alias for `nd`. 

684 

685 .. versionadded:: 1.12.0 

686 

687 Examples 

688 -------- 

689 >>> x = np.array([1, 2, 3]) 

690 >>> y = np.array([[4], [5], [6]]) 

691 >>> b = np.broadcast(x, y) 

692 >>> b.ndim 

693 2 

694 

695 """)) 

696 

697add_newdoc('numpy._core', 'broadcast', ('nd', 

698 """ 

699 Number of dimensions of broadcasted result. For code intended for NumPy 

700 1.12.0 and later the more consistent `ndim` is preferred. 

701 

702 Examples 

703 -------- 

704 >>> x = np.array([1, 2, 3]) 

705 >>> y = np.array([[4], [5], [6]]) 

706 >>> b = np.broadcast(x, y) 

707 >>> b.nd 

708 2 

709 

710 """)) 

711 

712add_newdoc('numpy._core', 'broadcast', ('numiter', 

713 """ 

714 Number of iterators possessed by the broadcasted result. 

715 

716 Examples 

717 -------- 

718 >>> x = np.array([1, 2, 3]) 

719 >>> y = np.array([[4], [5], [6]]) 

720 >>> b = np.broadcast(x, y) 

721 >>> b.numiter 

722 2 

723 

724 """)) 

725 

726add_newdoc('numpy._core', 'broadcast', ('shape', 

727 """ 

728 Shape of broadcasted result. 

729 

730 Examples 

731 -------- 

732 >>> x = np.array([1, 2, 3]) 

733 >>> y = np.array([[4], [5], [6]]) 

734 >>> b = np.broadcast(x, y) 

735 >>> b.shape 

736 (3, 3) 

737 

738 """)) 

739 

740add_newdoc('numpy._core', 'broadcast', ('size', 

741 """ 

742 Total size of broadcasted result. 

743 

744 Examples 

745 -------- 

746 >>> x = np.array([1, 2, 3]) 

747 >>> y = np.array([[4], [5], [6]]) 

748 >>> b = np.broadcast(x, y) 

749 >>> b.size 

750 9 

751 

752 """)) 

753 

754add_newdoc('numpy._core', 'broadcast', ('reset', 

755 """ 

756 reset() 

757 

758 Reset the broadcasted result's iterator(s). 

759 

760 Parameters 

761 ---------- 

762 None 

763 

764 Returns 

765 ------- 

766 None 

767 

768 Examples 

769 -------- 

770 >>> x = np.array([1, 2, 3]) 

771 >>> y = np.array([[4], [5], [6]]) 

772 >>> b = np.broadcast(x, y) 

773 >>> b.index 

774 0 

775 >>> next(b), next(b), next(b) 

776 ((1, 4), (2, 4), (3, 4)) 

777 >>> b.index 

778 3 

779 >>> b.reset() 

780 >>> b.index 

781 0 

782 

783 """)) 

784 

785############################################################################### 

786# 

787# numpy functions 

788# 

789############################################################################### 

790 

791add_newdoc('numpy._core.multiarray', 'array', 

792 """ 

793 array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, 

794 like=None) 

795 

796 Create an array. 

797 

798 Parameters 

799 ---------- 

800 object : array_like 

801 An array, any object exposing the array interface, an object whose 

802 ``__array__`` method returns an array, or any (nested) sequence. 

803 If object is a scalar, a 0-dimensional array containing object is 

804 returned. 

805 dtype : data-type, optional 

806 The desired data-type for the array. If not given, NumPy will try to use 

807 a default ``dtype`` that can represent the values (by applying promotion 

808 rules when necessary.) 

809 copy : bool, optional 

810 If ``True`` (default), then the array data is copied. If ``None``, 

811 a copy will only be made if ``__array__`` returns a copy, if obj is 

812 a nested sequence, or if a copy is needed to satisfy any of the other 

813 requirements (``dtype``, ``order``, etc.). Note that any copy of 

814 the data is shallow, i.e., for arrays with object dtype, the new 

815 array will point to the same objects. See Examples for `ndarray.copy`. 

816 For ``False`` it raises a ``ValueError`` if a copy cannot be avoided. 

817 Default: ``True``. 

818 order : {'K', 'A', 'C', 'F'}, optional 

819 Specify the memory layout of the array. If object is not an array, the 

820 newly created array will be in C order (row major) unless 'F' is 

821 specified, in which case it will be in Fortran order (column major). 

822 If object is an array the following holds. 

823 

824 ===== ========= =================================================== 

825 order no copy copy=True 

826 ===== ========= =================================================== 

827 'K' unchanged F & C order preserved, otherwise most similar order 

828 'A' unchanged F order if input is F and not C, otherwise C order 

829 'C' C order C order 

830 'F' F order F order 

831 ===== ========= =================================================== 

832 

833 When ``copy=None`` and a copy is made for other reasons, the result is 

834 the same as if ``copy=True``, with some exceptions for 'A', see the 

835 Notes section. The default order is 'K'. 

836 subok : bool, optional 

837 If True, then sub-classes will be passed-through, otherwise 

838 the returned array will be forced to be a base-class array (default). 

839 ndmin : int, optional 

840 Specifies the minimum number of dimensions that the resulting 

841 array should have. Ones will be prepended to the shape as 

842 needed to meet this requirement. 

843 ${ARRAY_FUNCTION_LIKE} 

844 

845 .. versionadded:: 1.20.0 

846 

847 Returns 

848 ------- 

849 out : ndarray 

850 An array object satisfying the specified requirements. 

851 

852 See Also 

853 -------- 

854 empty_like : Return an empty array with shape and type of input. 

855 ones_like : Return an array of ones with shape and type of input. 

856 zeros_like : Return an array of zeros with shape and type of input. 

857 full_like : Return a new array with shape of input filled with value. 

858 empty : Return a new uninitialized array. 

859 ones : Return a new array setting values to one. 

860 zeros : Return a new array setting values to zero. 

861 full : Return a new array of given shape filled with value. 

862 copy: Return an array copy of the given object. 

863 

864 

865 Notes 

866 ----- 

867 When order is 'A' and ``object`` is an array in neither 'C' nor 'F' order, 

868 and a copy is forced by a change in dtype, then the order of the result is 

869 not necessarily 'C' as expected. This is likely a bug. 

870 

871 Examples 

872 -------- 

873 >>> np.array([1, 2, 3]) 

874 array([1, 2, 3]) 

875 

876 Upcasting: 

877 

878 >>> np.array([1, 2, 3.0]) 

879 array([ 1., 2., 3.]) 

880 

881 More than one dimension: 

882 

883 >>> np.array([[1, 2], [3, 4]]) 

884 array([[1, 2], 

885 [3, 4]]) 

886 

887 Minimum dimensions 2: 

888 

889 >>> np.array([1, 2, 3], ndmin=2) 

890 array([[1, 2, 3]]) 

891 

892 Type provided: 

893 

894 >>> np.array([1, 2, 3], dtype=complex) 

895 array([ 1.+0.j, 2.+0.j, 3.+0.j]) 

896 

897 Data-type consisting of more than one element: 

898 

899 >>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')]) 

900 >>> x['a'] 

901 array([1, 3]) 

902 

903 Creating an array from sub-classes: 

904 

905 >>> np.array(np.asmatrix('1 2; 3 4')) 

906 array([[1, 2], 

907 [3, 4]]) 

908 

909 >>> np.array(np.asmatrix('1 2; 3 4'), subok=True) 

910 matrix([[1, 2], 

911 [3, 4]]) 

912 

913 """.replace( 

914 "${ARRAY_FUNCTION_LIKE}", 

915 array_function_like_doc, 

916 )) 

917 

918add_newdoc('numpy._core.multiarray', 'asarray', 

919 """ 

920 asarray(a, dtype=None, order=None, *, device=None, copy=None, like=None) 

921 

922 Convert the input to an array. 

923 

924 Parameters 

925 ---------- 

926 a : array_like 

927 Input data, in any form that can be converted to an array. This 

928 includes lists, lists of tuples, tuples, tuples of tuples, tuples 

929 of lists and ndarrays. 

930 dtype : data-type, optional 

931 By default, the data-type is inferred from the input data. 

932 order : {'C', 'F', 'A', 'K'}, optional 

933 Memory layout. 'A' and 'K' depend on the order of input array a. 

934 'C' row-major (C-style), 

935 'F' column-major (Fortran-style) memory representation. 

936 'A' (any) means 'F' if `a` is Fortran contiguous, 'C' otherwise 

937 'K' (keep) preserve input order 

938 Defaults to 'K'. 

939 device : str, optional 

940 The device on which to place the created array. Default: None. 

941 For Array-API interoperability only, so must be ``"cpu"`` if passed. 

942 

943 .. versionadded:: 2.0.0 

944 copy : bool, optional 

945 If ``True``, then the object is copied. If ``None`` then the object is 

946 copied only if needed, i.e. if ``__array__`` returns a copy, if obj 

947 is a nested sequence, or if a copy is needed to satisfy any of 

948 the other requirements (``dtype``, ``order``, etc.). 

949 For ``False`` it raises a ``ValueError`` if a copy cannot be avoided. 

950 Default: ``None``. 

951 ${ARRAY_FUNCTION_LIKE} 

952 

953 .. versionadded:: 1.20.0 

954 

955 Returns 

956 ------- 

957 out : ndarray 

958 Array interpretation of ``a``. No copy is performed if the input 

959 is already an ndarray with matching dtype and order. If ``a`` is a 

960 subclass of ndarray, a base class ndarray is returned. 

961 

962 See Also 

963 -------- 

964 asanyarray : Similar function which passes through subclasses. 

965 ascontiguousarray : Convert input to a contiguous array. 

966 asfortranarray : Convert input to an ndarray with column-major 

967 memory order. 

968 asarray_chkfinite : Similar function which checks input for NaNs and Infs. 

969 fromiter : Create an array from an iterator. 

970 fromfunction : Construct an array by executing a function on grid 

971 positions. 

972 

973 Examples 

974 -------- 

975 Convert a list into an array: 

976 

977 >>> a = [1, 2] 

978 >>> np.asarray(a) 

979 array([1, 2]) 

980 

981 Existing arrays are not copied: 

982 

983 >>> a = np.array([1, 2]) 

984 >>> np.asarray(a) is a 

985 True 

986 

987 If `dtype` is set, array is copied only if dtype does not match: 

988 

989 >>> a = np.array([1, 2], dtype=np.float32) 

990 >>> np.shares_memory(np.asarray(a, dtype=np.float32), a) 

991 True 

992 >>> np.shares_memory(np.asarray(a, dtype=np.float64), a) 

993 False 

994 

995 Contrary to `asanyarray`, ndarray subclasses are not passed through: 

996 

997 >>> issubclass(np.recarray, np.ndarray) 

998 True 

999 >>> a = np.array([(1., 2), (3., 4)], dtype='f4,i4').view(np.recarray) 

1000 >>> np.asarray(a) is a 

1001 False 

1002 >>> np.asanyarray(a) is a 

1003 True 

1004 

1005 """.replace( 

1006 "${ARRAY_FUNCTION_LIKE}", 

1007 array_function_like_doc, 

1008 )) 

1009 

1010add_newdoc('numpy._core.multiarray', 'asanyarray', 

1011 """ 

1012 asanyarray(a, dtype=None, order=None, *, like=None) 

1013 

1014 Convert the input to an ndarray, but pass ndarray subclasses through. 

1015 

1016 Parameters 

1017 ---------- 

1018 a : array_like 

1019 Input data, in any form that can be converted to an array. This 

1020 includes scalars, lists, lists of tuples, tuples, tuples of tuples, 

1021 tuples of lists, and ndarrays. 

1022 dtype : data-type, optional 

1023 By default, the data-type is inferred from the input data. 

1024 order : {'C', 'F', 'A', 'K'}, optional 

1025 Memory layout. 'A' and 'K' depend on the order of input array a. 

1026 'C' row-major (C-style), 

1027 'F' column-major (Fortran-style) memory representation. 

1028 'A' (any) means 'F' if `a` is Fortran contiguous, 'C' otherwise 

1029 'K' (keep) preserve input order 

1030 Defaults to 'C'. 

1031 ${ARRAY_FUNCTION_LIKE} 

1032 

1033 .. versionadded:: 1.20.0 

1034 

1035 Returns 

1036 ------- 

1037 out : ndarray or an ndarray subclass 

1038 Array interpretation of `a`. If `a` is an ndarray or a subclass 

1039 of ndarray, it is returned as-is and no copy is performed. 

1040 

1041 See Also 

1042 -------- 

1043 asarray : Similar function which always returns ndarrays. 

1044 ascontiguousarray : Convert input to a contiguous array. 

1045 asfortranarray : Convert input to an ndarray with column-major 

1046 memory order. 

1047 asarray_chkfinite : Similar function which checks input for NaNs and 

1048 Infs. 

1049 fromiter : Create an array from an iterator. 

1050 fromfunction : Construct an array by executing a function on grid 

1051 positions. 

1052 

1053 Examples 

1054 -------- 

1055 Convert a list into an array: 

1056 

1057 >>> a = [1, 2] 

1058 >>> np.asanyarray(a) 

1059 array([1, 2]) 

1060 

1061 Instances of `ndarray` subclasses are passed through as-is: 

1062 

1063 >>> a = np.array([(1., 2), (3., 4)], dtype='f4,i4').view(np.recarray) 

1064 >>> np.asanyarray(a) is a 

1065 True 

1066 

1067 """.replace( 

1068 "${ARRAY_FUNCTION_LIKE}", 

1069 array_function_like_doc, 

1070 )) 

1071 

1072add_newdoc('numpy._core.multiarray', 'ascontiguousarray', 

1073 """ 

1074 ascontiguousarray(a, dtype=None, *, like=None) 

1075 

1076 Return a contiguous array (ndim >= 1) in memory (C order). 

1077 

1078 Parameters 

1079 ---------- 

1080 a : array_like 

1081 Input array. 

1082 dtype : str or dtype object, optional 

1083 Data-type of returned array. 

1084 ${ARRAY_FUNCTION_LIKE} 

1085 

1086 .. versionadded:: 1.20.0 

1087 

1088 Returns 

1089 ------- 

1090 out : ndarray 

1091 Contiguous array of same shape and content as `a`, with type `dtype` 

1092 if specified. 

1093 

1094 See Also 

1095 -------- 

1096 asfortranarray : Convert input to an ndarray with column-major 

1097 memory order. 

1098 require : Return an ndarray that satisfies requirements. 

1099 ndarray.flags : Information about the memory layout of the array. 

1100 

1101 Examples 

1102 -------- 

1103 Starting with a Fortran-contiguous array: 

1104 

1105 >>> x = np.ones((2, 3), order='F') 

1106 >>> x.flags['F_CONTIGUOUS'] 

1107 True 

1108 

1109 Calling ``ascontiguousarray`` makes a C-contiguous copy: 

1110 

1111 >>> y = np.ascontiguousarray(x) 

1112 >>> y.flags['C_CONTIGUOUS'] 

1113 True 

1114 >>> np.may_share_memory(x, y) 

1115 False 

1116 

1117 Now, starting with a C-contiguous array: 

1118 

1119 >>> x = np.ones((2, 3), order='C') 

1120 >>> x.flags['C_CONTIGUOUS'] 

1121 True 

1122 

1123 Then, calling ``ascontiguousarray`` returns the same object: 

1124 

1125 >>> y = np.ascontiguousarray(x) 

1126 >>> x is y 

1127 True 

1128 

1129 Note: This function returns an array with at least one-dimension (1-d) 

1130 so it will not preserve 0-d arrays. 

1131 

1132 """.replace( 

1133 "${ARRAY_FUNCTION_LIKE}", 

1134 array_function_like_doc, 

1135 )) 

1136 

1137add_newdoc('numpy._core.multiarray', 'asfortranarray', 

1138 """ 

1139 asfortranarray(a, dtype=None, *, like=None) 

1140 

1141 Return an array (ndim >= 1) laid out in Fortran order in memory. 

1142 

1143 Parameters 

1144 ---------- 

1145 a : array_like 

1146 Input array. 

1147 dtype : str or dtype object, optional 

1148 By default, the data-type is inferred from the input data. 

1149 ${ARRAY_FUNCTION_LIKE} 

1150 

1151 .. versionadded:: 1.20.0 

1152 

1153 Returns 

1154 ------- 

1155 out : ndarray 

1156 The input `a` in Fortran, or column-major, order. 

1157 

1158 See Also 

1159 -------- 

1160 ascontiguousarray : Convert input to a contiguous (C order) array. 

1161 asanyarray : Convert input to an ndarray with either row or 

1162 column-major memory order. 

1163 require : Return an ndarray that satisfies requirements. 

1164 ndarray.flags : Information about the memory layout of the array. 

1165 

1166 Examples 

1167 -------- 

1168 Starting with a C-contiguous array: 

1169 

1170 >>> x = np.ones((2, 3), order='C') 

1171 >>> x.flags['C_CONTIGUOUS'] 

1172 True 

1173 

1174 Calling ``asfortranarray`` makes a Fortran-contiguous copy: 

1175 

1176 >>> y = np.asfortranarray(x) 

1177 >>> y.flags['F_CONTIGUOUS'] 

1178 True 

1179 >>> np.may_share_memory(x, y) 

1180 False 

1181 

1182 Now, starting with a Fortran-contiguous array: 

1183 

1184 >>> x = np.ones((2, 3), order='F') 

1185 >>> x.flags['F_CONTIGUOUS'] 

1186 True 

1187 

1188 Then, calling ``asfortranarray`` returns the same object: 

1189 

1190 >>> y = np.asfortranarray(x) 

1191 >>> x is y 

1192 True 

1193 

1194 Note: This function returns an array with at least one-dimension (1-d) 

1195 so it will not preserve 0-d arrays. 

1196 

1197 """.replace( 

1198 "${ARRAY_FUNCTION_LIKE}", 

1199 array_function_like_doc, 

1200 )) 

1201 

1202add_newdoc('numpy._core.multiarray', 'empty', 

1203 """ 

1204 empty(shape, dtype=float, order='C', *, device=None, like=None) 

1205 

1206 Return a new array of given shape and type, without initializing entries. 

1207 

1208 Parameters 

1209 ---------- 

1210 shape : int or tuple of int 

1211 Shape of the empty array, e.g., ``(2, 3)`` or ``2``. 

1212 dtype : data-type, optional 

1213 Desired output data-type for the array, e.g, `numpy.int8`. Default is 

1214 `numpy.float64`. 

1215 order : {'C', 'F'}, optional, default: 'C' 

1216 Whether to store multi-dimensional data in row-major 

1217 (C-style) or column-major (Fortran-style) order in 

1218 memory. 

1219 device : str, optional 

1220 The device on which to place the created array. Default: None. 

1221 For Array-API interoperability only, so must be ``"cpu"`` if passed. 

1222 

1223 .. versionadded:: 2.0.0 

1224 ${ARRAY_FUNCTION_LIKE} 

1225 

1226 .. versionadded:: 1.20.0 

1227 

1228 Returns 

1229 ------- 

1230 out : ndarray 

1231 Array of uninitialized (arbitrary) data of the given shape, dtype, and 

1232 order. Object arrays will be initialized to None. 

1233 

1234 See Also 

1235 -------- 

1236 empty_like : Return an empty array with shape and type of input. 

1237 ones : Return a new array setting values to one. 

1238 zeros : Return a new array setting values to zero. 

1239 full : Return a new array of given shape filled with value. 

1240 

1241 Notes 

1242 ----- 

1243 Unlike other array creation functions (e.g. `zeros`, `ones`, `full`), 

1244 `empty` does not initialize the values of the array, and may therefore be 

1245 marginally faster. However, the values stored in the newly allocated array 

1246 are arbitrary. For reproducible behavior, be sure to set each element of 

1247 the array before reading. 

1248 

1249 Examples 

1250 -------- 

1251 >>> np.empty([2, 2]) 

1252 array([[ -9.74499359e+001, 6.69583040e-309], 

1253 [ 2.13182611e-314, 3.06959433e-309]]) #uninitialized 

1254 

1255 >>> np.empty([2, 2], dtype=int) 

1256 array([[-1073741821, -1067949133], 

1257 [ 496041986, 19249760]]) #uninitialized 

1258 

1259 """.replace( 

1260 "${ARRAY_FUNCTION_LIKE}", 

1261 array_function_like_doc, 

1262 )) 

1263 

1264add_newdoc('numpy._core.multiarray', 'scalar', 

1265 """ 

1266 scalar(dtype, obj) 

1267 

1268 Return a new scalar array of the given type initialized with obj. 

1269 

1270 This function is meant mainly for pickle support. `dtype` must be a 

1271 valid data-type descriptor. If `dtype` corresponds to an object 

1272 descriptor, then `obj` can be any object, otherwise `obj` must be a 

1273 string. If `obj` is not given, it will be interpreted as None for object 

1274 type and as zeros for all other types. 

1275 

1276 """) 

1277 

1278add_newdoc('numpy._core.multiarray', 'zeros', 

1279 """ 

1280 zeros(shape, dtype=float, order='C', *, like=None) 

1281 

1282 Return a new array of given shape and type, filled with zeros. 

1283 

1284 Parameters 

1285 ---------- 

1286 shape : int or tuple of ints 

1287 Shape of the new array, e.g., ``(2, 3)`` or ``2``. 

1288 dtype : data-type, optional 

1289 The desired data-type for the array, e.g., `numpy.int8`. Default is 

1290 `numpy.float64`. 

1291 order : {'C', 'F'}, optional, default: 'C' 

1292 Whether to store multi-dimensional data in row-major 

1293 (C-style) or column-major (Fortran-style) order in 

1294 memory. 

1295 ${ARRAY_FUNCTION_LIKE} 

1296 

1297 .. versionadded:: 1.20.0 

1298 

1299 Returns 

1300 ------- 

1301 out : ndarray 

1302 Array of zeros with the given shape, dtype, and order. 

1303 

1304 See Also 

1305 -------- 

1306 zeros_like : Return an array of zeros with shape and type of input. 

1307 empty : Return a new uninitialized array. 

1308 ones : Return a new array setting values to one. 

1309 full : Return a new array of given shape filled with value. 

1310 

1311 Examples 

1312 -------- 

1313 >>> np.zeros(5) 

1314 array([ 0., 0., 0., 0., 0.]) 

1315 

1316 >>> np.zeros((5,), dtype=int) 

1317 array([0, 0, 0, 0, 0]) 

1318 

1319 >>> np.zeros((2, 1)) 

1320 array([[ 0.], 

1321 [ 0.]]) 

1322 

1323 >>> s = (2,2) 

1324 >>> np.zeros(s) 

1325 array([[ 0., 0.], 

1326 [ 0., 0.]]) 

1327 

1328 >>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype 

1329 array([(0, 0), (0, 0)], 

1330 dtype=[('x', '<i4'), ('y', '<i4')]) 

1331 

1332 """.replace( 

1333 "${ARRAY_FUNCTION_LIKE}", 

1334 array_function_like_doc, 

1335 )) 

1336 

1337add_newdoc('numpy._core.multiarray', 'set_typeDict', 

1338 """set_typeDict(dict) 

1339 

1340 Set the internal dictionary that can look up an array type using a 

1341 registered code. 

1342 

1343 """) 

1344 

1345add_newdoc('numpy._core.multiarray', 'fromstring', 

1346 """ 

1347 fromstring(string, dtype=float, count=-1, *, sep, like=None) 

1348 

1349 A new 1-D array initialized from text data in a string. 

1350 

1351 Parameters 

1352 ---------- 

1353 string : str 

1354 A string containing the data. 

1355 dtype : data-type, optional 

1356 The data type of the array; default: float. For binary input data, 

1357 the data must be in exactly this format. Most builtin numeric types are 

1358 supported and extension types may be supported. 

1359 

1360 .. versionadded:: 1.18.0 

1361 Complex dtypes. 

1362 

1363 count : int, optional 

1364 Read this number of `dtype` elements from the data. If this is 

1365 negative (the default), the count will be determined from the 

1366 length of the data. 

1367 sep : str, optional 

1368 The string separating numbers in the data; extra whitespace between 

1369 elements is also ignored. 

1370 

1371 .. deprecated:: 1.14 

1372 Passing ``sep=''``, the default, is deprecated since it will 

1373 trigger the deprecated binary mode of this function. This mode 

1374 interprets `string` as binary bytes, rather than ASCII text with 

1375 decimal numbers, an operation which is better spelt 

1376 ``frombuffer(string, dtype, count)``. If `string` contains unicode 

1377 text, the binary mode of `fromstring` will first encode it into 

1378 bytes using utf-8, which will not produce sane results. 

1379 

1380 ${ARRAY_FUNCTION_LIKE} 

1381 

1382 .. versionadded:: 1.20.0 

1383 

1384 Returns 

1385 ------- 

1386 arr : ndarray 

1387 The constructed array. 

1388 

1389 Raises 

1390 ------ 

1391 ValueError 

1392 If the string is not the correct size to satisfy the requested 

1393 `dtype` and `count`. 

1394 

1395 See Also 

1396 -------- 

1397 frombuffer, fromfile, fromiter 

1398 

1399 Examples 

1400 -------- 

1401 >>> np.fromstring('1 2', dtype=int, sep=' ') 

1402 array([1, 2]) 

1403 >>> np.fromstring('1, 2', dtype=int, sep=',') 

1404 array([1, 2]) 

1405 

1406 """.replace( 

1407 "${ARRAY_FUNCTION_LIKE}", 

1408 array_function_like_doc, 

1409 )) 

1410 

1411add_newdoc('numpy._core.multiarray', 'compare_chararrays', 

1412 """ 

1413 compare_chararrays(a1, a2, cmp, rstrip) 

1414 

1415 Performs element-wise comparison of two string arrays using the 

1416 comparison operator specified by `cmp`. 

1417 

1418 Parameters 

1419 ---------- 

1420 a1, a2 : array_like 

1421 Arrays to be compared. 

1422 cmp : {"<", "<=", "==", ">=", ">", "!="} 

1423 Type of comparison. 

1424 rstrip : Boolean 

1425 If True, the spaces at the end of Strings are removed before the comparison. 

1426 

1427 Returns 

1428 ------- 

1429 out : ndarray 

1430 The output array of type Boolean with the same shape as a and b. 

1431 

1432 Raises 

1433 ------ 

1434 ValueError 

1435 If `cmp` is not valid. 

1436 TypeError 

1437 If at least one of `a` or `b` is a non-string array 

1438 

1439 Examples 

1440 -------- 

1441 >>> a = np.array(["a", "b", "cde"]) 

1442 >>> b = np.array(["a", "a", "dec"]) 

1443 >>> np.char.compare_chararrays(a, b, ">", True) 

1444 array([False, True, False]) 

1445 

1446 """) 

1447 

1448add_newdoc('numpy._core.multiarray', 'fromiter', 

1449 """ 

1450 fromiter(iter, dtype, count=-1, *, like=None) 

1451 

1452 Create a new 1-dimensional array from an iterable object. 

1453 

1454 Parameters 

1455 ---------- 

1456 iter : iterable object 

1457 An iterable object providing data for the array. 

1458 dtype : data-type 

1459 The data-type of the returned array. 

1460 

1461 .. versionchanged:: 1.23 

1462 Object and subarray dtypes are now supported (note that the final 

1463 result is not 1-D for a subarray dtype). 

1464 

1465 count : int, optional 

1466 The number of items to read from *iterable*. The default is -1, 

1467 which means all data is read. 

1468 ${ARRAY_FUNCTION_LIKE} 

1469 

1470 .. versionadded:: 1.20.0 

1471 

1472 Returns 

1473 ------- 

1474 out : ndarray 

1475 The output array. 

1476 

1477 Notes 

1478 ----- 

1479 Specify `count` to improve performance. It allows ``fromiter`` to 

1480 pre-allocate the output array, instead of resizing it on demand. 

1481 

1482 Examples 

1483 -------- 

1484 >>> iterable = (x*x for x in range(5)) 

1485 >>> np.fromiter(iterable, float) 

1486 array([ 0., 1., 4., 9., 16.]) 

1487 

1488 A carefully constructed subarray dtype will lead to higher dimensional 

1489 results: 

1490 

1491 >>> iterable = ((x+1, x+2) for x in range(5)) 

1492 >>> np.fromiter(iterable, dtype=np.dtype((int, 2))) 

1493 array([[1, 2], 

1494 [2, 3], 

1495 [3, 4], 

1496 [4, 5], 

1497 [5, 6]]) 

1498 

1499 

1500 """.replace( 

1501 "${ARRAY_FUNCTION_LIKE}", 

1502 array_function_like_doc, 

1503 )) 

1504 

1505add_newdoc('numpy._core.multiarray', 'fromfile', 

1506 """ 

1507 fromfile(file, dtype=float, count=-1, sep='', offset=0, *, like=None) 

1508 

1509 Construct an array from data in a text or binary file. 

1510 

1511 A highly efficient way of reading binary data with a known data-type, 

1512 as well as parsing simply formatted text files. Data written using the 

1513 `tofile` method can be read using this function. 

1514 

1515 Parameters 

1516 ---------- 

1517 file : file or str or Path 

1518 Open file object or filename. 

1519 

1520 .. versionchanged:: 1.17.0 

1521 `pathlib.Path` objects are now accepted. 

1522 

1523 dtype : data-type 

1524 Data type of the returned array. 

1525 For binary files, it is used to determine the size and byte-order 

1526 of the items in the file. 

1527 Most builtin numeric types are supported and extension types may be supported. 

1528 

1529 .. versionadded:: 1.18.0 

1530 Complex dtypes. 

1531 

1532 count : int 

1533 Number of items to read. ``-1`` means all items (i.e., the complete 

1534 file). 

1535 sep : str 

1536 Separator between items if file is a text file. 

1537 Empty ("") separator means the file should be treated as binary. 

1538 Spaces (" ") in the separator match zero or more whitespace characters. 

1539 A separator consisting only of spaces must match at least one 

1540 whitespace. 

1541 offset : int 

1542 The offset (in bytes) from the file's current position. Defaults to 0. 

1543 Only permitted for binary files. 

1544 

1545 .. versionadded:: 1.17.0 

1546 ${ARRAY_FUNCTION_LIKE} 

1547 

1548 .. versionadded:: 1.20.0 

1549 

1550 See also 

1551 -------- 

1552 load, save 

1553 ndarray.tofile 

1554 loadtxt : More flexible way of loading data from a text file. 

1555 

1556 Notes 

1557 ----- 

1558 Do not rely on the combination of `tofile` and `fromfile` for 

1559 data storage, as the binary files generated are not platform 

1560 independent. In particular, no byte-order or data-type information is 

1561 saved. Data can be stored in the platform independent ``.npy`` format 

1562 using `save` and `load` instead. 

1563 

1564 Examples 

1565 -------- 

1566 Construct an ndarray: 

1567 

1568 >>> dt = np.dtype([('time', [('min', np.int64), ('sec', np.int64)]), 

1569 ... ('temp', float)]) 

1570 >>> x = np.zeros((1,), dtype=dt) 

1571 >>> x['time']['min'] = 10; x['temp'] = 98.25 

1572 >>> x 

1573 array([((10, 0), 98.25)], 

1574 dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')]) 

1575 

1576 Save the raw data to disk: 

1577 

1578 >>> import tempfile 

1579 >>> fname = tempfile.mkstemp()[1] 

1580 >>> x.tofile(fname) 

1581 

1582 Read the raw data from disk: 

1583 

1584 >>> np.fromfile(fname, dtype=dt) 

1585 array([((10, 0), 98.25)], 

1586 dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')]) 

1587 

1588 The recommended way to store and load data: 

1589 

1590 >>> np.save(fname, x) 

1591 >>> np.load(fname + '.npy') 

1592 array([((10, 0), 98.25)], 

1593 dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')]) 

1594 

1595 """.replace( 

1596 "${ARRAY_FUNCTION_LIKE}", 

1597 array_function_like_doc, 

1598 )) 

1599 

1600add_newdoc('numpy._core.multiarray', 'frombuffer', 

1601 """ 

1602 frombuffer(buffer, dtype=float, count=-1, offset=0, *, like=None) 

1603 

1604 Interpret a buffer as a 1-dimensional array. 

1605 

1606 Parameters 

1607 ---------- 

1608 buffer : buffer_like 

1609 An object that exposes the buffer interface. 

1610 dtype : data-type, optional 

1611 Data-type of the returned array; default: float. 

1612 count : int, optional 

1613 Number of items to read. ``-1`` means all data in the buffer. 

1614 offset : int, optional 

1615 Start reading the buffer from this offset (in bytes); default: 0. 

1616 ${ARRAY_FUNCTION_LIKE} 

1617 

1618 .. versionadded:: 1.20.0 

1619 

1620 Returns 

1621 ------- 

1622 out : ndarray 

1623 

1624 See also 

1625 -------- 

1626 ndarray.tobytes 

1627 Inverse of this operation, construct Python bytes from the raw data 

1628 bytes in the array. 

1629 

1630 Notes 

1631 ----- 

1632 If the buffer has data that is not in machine byte-order, this should 

1633 be specified as part of the data-type, e.g.:: 

1634 

1635 >>> dt = np.dtype(int) 

1636 >>> dt = dt.newbyteorder('>') 

1637 >>> np.frombuffer(buf, dtype=dt) # doctest: +SKIP 

1638 

1639 The data of the resulting array will not be byteswapped, but will be 

1640 interpreted correctly. 

1641 

1642 This function creates a view into the original object. This should be safe 

1643 in general, but it may make sense to copy the result when the original 

1644 object is mutable or untrusted. 

1645 

1646 Examples 

1647 -------- 

1648 >>> s = b'hello world' 

1649 >>> np.frombuffer(s, dtype='S1', count=5, offset=6) 

1650 array([b'w', b'o', b'r', b'l', b'd'], dtype='|S1') 

1651 

1652 >>> np.frombuffer(b'\\x01\\x02', dtype=np.uint8) 

1653 array([1, 2], dtype=uint8) 

1654 >>> np.frombuffer(b'\\x01\\x02\\x03\\x04\\x05', dtype=np.uint8, count=3) 

1655 array([1, 2, 3], dtype=uint8) 

1656 

1657 """.replace( 

1658 "${ARRAY_FUNCTION_LIKE}", 

1659 array_function_like_doc, 

1660 )) 

1661 

1662add_newdoc('numpy._core.multiarray', 'from_dlpack', 

1663 """ 

1664 from_dlpack(x, /) 

1665 

1666 Create a NumPy array from an object implementing the ``__dlpack__`` 

1667 protocol. Generally, the returned NumPy array is a read-only view 

1668 of the input object. See [1]_ and [2]_ for more details. 

1669 

1670 Parameters 

1671 ---------- 

1672 x : object 

1673 A Python object that implements the ``__dlpack__`` and 

1674 ``__dlpack_device__`` methods. 

1675 

1676 Returns 

1677 ------- 

1678 out : ndarray 

1679 

1680 References 

1681 ---------- 

1682 .. [1] Array API documentation, 

1683 https://data-apis.org/array-api/latest/design_topics/data_interchange.html#syntax-for-data-interchange-with-dlpack 

1684 

1685 .. [2] Python specification for DLPack, 

1686 https://dmlc.github.io/dlpack/latest/python_spec.html 

1687 

1688 Examples 

1689 -------- 

1690 >>> import torch # doctest: +SKIP 

1691 >>> x = torch.arange(10) # doctest: +SKIP 

1692 >>> # create a view of the torch tensor "x" in NumPy 

1693 >>> y = np.from_dlpack(x) # doctest: +SKIP 

1694 """) 

1695 

1696add_newdoc('numpy._core.multiarray', 'correlate', 

1697 """cross_correlate(a,v, mode=0)""") 

1698 

1699add_newdoc('numpy._core.multiarray', 'arange', 

1700 """ 

1701 arange([start,] stop[, step,], dtype=None, *, device=None, like=None) 

1702 

1703 Return evenly spaced values within a given interval. 

1704 

1705 ``arange`` can be called with a varying number of positional arguments: 

1706 

1707 * ``arange(stop)``: Values are generated within the half-open interval 

1708 ``[0, stop)`` (in other words, the interval including `start` but 

1709 excluding `stop`). 

1710 * ``arange(start, stop)``: Values are generated within the half-open 

1711 interval ``[start, stop)``. 

1712 * ``arange(start, stop, step)`` Values are generated within the half-open 

1713 interval ``[start, stop)``, with spacing between values given by 

1714 ``step``. 

1715 

1716 For integer arguments the function is roughly equivalent to the Python 

1717 built-in :py:class:`range`, but returns an ndarray rather than a ``range`` 

1718 instance. 

1719 

1720 When using a non-integer step, such as 0.1, it is often better to use 

1721 `numpy.linspace`. 

1722 

1723 See the Warning sections below for more information. 

1724 

1725 Parameters 

1726 ---------- 

1727 start : integer or real, optional 

1728 Start of interval. The interval includes this value. The default 

1729 start value is 0. 

1730 stop : integer or real 

1731 End of interval. The interval does not include this value, except 

1732 in some cases where `step` is not an integer and floating point 

1733 round-off affects the length of `out`. 

1734 step : integer or real, optional 

1735 Spacing between values. For any output `out`, this is the distance 

1736 between two adjacent values, ``out[i+1] - out[i]``. The default 

1737 step size is 1. If `step` is specified as a position argument, 

1738 `start` must also be given. 

1739 dtype : dtype, optional 

1740 The type of the output array. If `dtype` is not given, infer the data 

1741 type from the other input arguments. 

1742 device : str, optional 

1743 The device on which to place the created array. Default: None. 

1744 For Array-API interoperability only, so must be ``"cpu"`` if passed. 

1745 

1746 .. versionadded:: 2.0.0 

1747 ${ARRAY_FUNCTION_LIKE} 

1748 

1749 .. versionadded:: 1.20.0 

1750 

1751 Returns 

1752 ------- 

1753 arange : ndarray 

1754 Array of evenly spaced values. 

1755 

1756 For floating point arguments, the length of the result is 

1757 ``ceil((stop - start)/step)``. Because of floating point overflow, 

1758 this rule may result in the last element of `out` being greater 

1759 than `stop`. 

1760 

1761 Warnings 

1762 -------- 

1763 The length of the output might not be numerically stable. 

1764 

1765 Another stability issue is due to the internal implementation of 

1766 `numpy.arange`. 

1767 The actual step value used to populate the array is 

1768 ``dtype(start + step) - dtype(start)`` and not `step`. Precision loss 

1769 can occur here, due to casting or due to using floating points when 

1770 `start` is much larger than `step`. This can lead to unexpected 

1771 behaviour. For example:: 

1772 

1773 >>> np.arange(0, 5, 0.5, dtype=int) 

1774 array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) 

1775 >>> np.arange(-3, 3, 0.5, dtype=int) 

1776 array([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8]) 

1777 

1778 In such cases, the use of `numpy.linspace` should be preferred. 

1779 

1780 The built-in :py:class:`range` generates :std:doc:`Python built-in integers 

1781 that have arbitrary size <python:c-api/long>`, while `numpy.arange` 

1782 produces `numpy.int32` or `numpy.int64` numbers. This may result in 

1783 incorrect results for large integer values:: 

1784 

1785 >>> power = 40 

1786 >>> modulo = 10000 

1787 >>> x1 = [(n ** power) % modulo for n in range(8)] 

1788 >>> x2 = [(n ** power) % modulo for n in np.arange(8)] 

1789 >>> print(x1) 

1790 [0, 1, 7776, 8801, 6176, 625, 6576, 4001] # correct 

1791 >>> print(x2) 

1792 [0, 1, 7776, 7185, 0, 5969, 4816, 3361] # incorrect 

1793 

1794 See Also 

1795 -------- 

1796 numpy.linspace : Evenly spaced numbers with careful handling of endpoints. 

1797 numpy.ogrid: Arrays of evenly spaced numbers in N-dimensions. 

1798 numpy.mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions. 

1799 :ref:`how-to-partition` 

1800 

1801 Examples 

1802 -------- 

1803 >>> np.arange(3) 

1804 array([0, 1, 2]) 

1805 >>> np.arange(3.0) 

1806 array([ 0., 1., 2.]) 

1807 >>> np.arange(3,7) 

1808 array([3, 4, 5, 6]) 

1809 >>> np.arange(3,7,2) 

1810 array([3, 5]) 

1811 

1812 """.replace( 

1813 "${ARRAY_FUNCTION_LIKE}", 

1814 array_function_like_doc, 

1815 )) 

1816 

1817add_newdoc('numpy._core.multiarray', '_get_ndarray_c_version', 

1818 """_get_ndarray_c_version() 

1819 

1820 Return the compile time NPY_VERSION (formerly called NDARRAY_VERSION) number. 

1821 

1822 """) 

1823 

1824add_newdoc('numpy._core.multiarray', '_reconstruct', 

1825 """_reconstruct(subtype, shape, dtype) 

1826 

1827 Construct an empty array. Used by Pickles. 

1828 

1829 """) 

1830 

1831 

1832add_newdoc('numpy._core.multiarray', 'set_string_function', 

1833 """ 

1834 set_string_function(f, repr=1) 

1835 

1836 Internal method to set a function to be used when pretty printing arrays. 

1837 

1838 """) 

1839 

1840add_newdoc('numpy._core.multiarray', 'promote_types', 

1841 """ 

1842 promote_types(type1, type2) 

1843 

1844 Returns the data type with the smallest size and smallest scalar 

1845 kind to which both ``type1`` and ``type2`` may be safely cast. 

1846 The returned data type is always considered "canonical", this mainly 

1847 means that the promoted dtype will always be in native byte order. 

1848 

1849 This function is symmetric, but rarely associative. 

1850 

1851 Parameters 

1852 ---------- 

1853 type1 : dtype or dtype specifier 

1854 First data type. 

1855 type2 : dtype or dtype specifier 

1856 Second data type. 

1857 

1858 Returns 

1859 ------- 

1860 out : dtype 

1861 The promoted data type. 

1862 

1863 Notes 

1864 ----- 

1865 Please see `numpy.result_type` for additional information about promotion. 

1866 

1867 .. versionadded:: 1.6.0 

1868 

1869 Starting in NumPy 1.9, promote_types function now returns a valid string 

1870 length when given an integer or float dtype as one argument and a string 

1871 dtype as another argument. Previously it always returned the input string 

1872 dtype, even if it wasn't long enough to store the max integer/float value 

1873 converted to a string. 

1874 

1875 .. versionchanged:: 1.23.0 

1876 

1877 NumPy now supports promotion for more structured dtypes. It will now 

1878 remove unnecessary padding from a structure dtype and promote included 

1879 fields individually. 

1880 

1881 See Also 

1882 -------- 

1883 result_type, dtype, can_cast 

1884 

1885 Examples 

1886 -------- 

1887 >>> np.promote_types('f4', 'f8') 

1888 dtype('float64') 

1889 

1890 >>> np.promote_types('i8', 'f4') 

1891 dtype('float64') 

1892 

1893 >>> np.promote_types('>i8', '<c8') 

1894 dtype('complex128') 

1895 

1896 >>> np.promote_types('i4', 'S8') 

1897 dtype('S11') 

1898 

1899 An example of a non-associative case: 

1900 

1901 >>> p = np.promote_types 

1902 >>> p('S', p('i1', 'u1')) 

1903 dtype('S6') 

1904 >>> p(p('S', 'i1'), 'u1') 

1905 dtype('S4') 

1906 

1907 """) 

1908 

1909add_newdoc('numpy._core.multiarray', 'c_einsum', 

1910 """ 

1911 c_einsum(subscripts, *operands, out=None, dtype=None, order='K', 

1912 casting='safe') 

1913 

1914 *This documentation shadows that of the native python implementation of the `einsum` function, 

1915 except all references and examples related to the `optimize` argument (v 0.12.0) have been removed.* 

1916 

1917 Evaluates the Einstein summation convention on the operands. 

1918 

1919 Using the Einstein summation convention, many common multi-dimensional, 

1920 linear algebraic array operations can be represented in a simple fashion. 

1921 In *implicit* mode `einsum` computes these values. 

1922 

1923 In *explicit* mode, `einsum` provides further flexibility to compute 

1924 other array operations that might not be considered classical Einstein 

1925 summation operations, by disabling, or forcing summation over specified 

1926 subscript labels. 

1927 

1928 See the notes and examples for clarification. 

1929 

1930 Parameters 

1931 ---------- 

1932 subscripts : str 

1933 Specifies the subscripts for summation as comma separated list of 

1934 subscript labels. An implicit (classical Einstein summation) 

1935 calculation is performed unless the explicit indicator '->' is 

1936 included as well as subscript labels of the precise output form. 

1937 operands : list of array_like 

1938 These are the arrays for the operation. 

1939 out : ndarray, optional 

1940 If provided, the calculation is done into this array. 

1941 dtype : {data-type, None}, optional 

1942 If provided, forces the calculation to use the data type specified. 

1943 Note that you may have to also give a more liberal `casting` 

1944 parameter to allow the conversions. Default is None. 

1945 order : {'C', 'F', 'A', 'K'}, optional 

1946 Controls the memory layout of the output. 'C' means it should 

1947 be C contiguous. 'F' means it should be Fortran contiguous, 

1948 'A' means it should be 'F' if the inputs are all 'F', 'C' otherwise. 

1949 'K' means it should be as close to the layout of the inputs as 

1950 is possible, including arbitrarily permuted axes. 

1951 Default is 'K'. 

1952 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional 

1953 Controls what kind of data casting may occur. Setting this to 

1954 'unsafe' is not recommended, as it can adversely affect accumulations. 

1955 

1956 * 'no' means the data types should not be cast at all. 

1957 * 'equiv' means only byte-order changes are allowed. 

1958 * 'safe' means only casts which can preserve values are allowed. 

1959 * 'same_kind' means only safe casts or casts within a kind, 

1960 like float64 to float32, are allowed. 

1961 * 'unsafe' means any data conversions may be done. 

1962 

1963 Default is 'safe'. 

1964 optimize : {False, True, 'greedy', 'optimal'}, optional 

1965 Controls if intermediate optimization should occur. No optimization 

1966 will occur if False and True will default to the 'greedy' algorithm. 

1967 Also accepts an explicit contraction list from the ``np.einsum_path`` 

1968 function. See ``np.einsum_path`` for more details. Defaults to False. 

1969 

1970 Returns 

1971 ------- 

1972 output : ndarray 

1973 The calculation based on the Einstein summation convention. 

1974 

1975 See Also 

1976 -------- 

1977 einsum_path, dot, inner, outer, tensordot, linalg.multi_dot 

1978 

1979 Notes 

1980 ----- 

1981 .. versionadded:: 1.6.0 

1982 

1983 The Einstein summation convention can be used to compute 

1984 many multi-dimensional, linear algebraic array operations. `einsum` 

1985 provides a succinct way of representing these. 

1986 

1987 A non-exhaustive list of these operations, 

1988 which can be computed by `einsum`, is shown below along with examples: 

1989 

1990 * Trace of an array, :py:func:`numpy.trace`. 

1991 * Return a diagonal, :py:func:`numpy.diag`. 

1992 * Array axis summations, :py:func:`numpy.sum`. 

1993 * Transpositions and permutations, :py:func:`numpy.transpose`. 

1994 * Matrix multiplication and dot product, :py:func:`numpy.matmul` :py:func:`numpy.dot`. 

1995 * Vector inner and outer products, :py:func:`numpy.inner` :py:func:`numpy.outer`. 

1996 * Broadcasting, element-wise and scalar multiplication, :py:func:`numpy.multiply`. 

1997 * Tensor contractions, :py:func:`numpy.tensordot`. 

1998 * Chained array operations, in efficient calculation order, :py:func:`numpy.einsum_path`. 

1999 

2000 The subscripts string is a comma-separated list of subscript labels, 

2001 where each label refers to a dimension of the corresponding operand. 

2002 Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)`` 

2003 is equivalent to :py:func:`np.inner(a,b) <numpy.inner>`. If a label 

2004 appears only once, it is not summed, so ``np.einsum('i', a)`` produces a 

2005 view of ``a`` with no changes. A further example ``np.einsum('ij,jk', a, b)`` 

2006 describes traditional matrix multiplication and is equivalent to 

2007 :py:func:`np.matmul(a,b) <numpy.matmul>`. Repeated subscript labels in one 

2008 operand take the diagonal. For example, ``np.einsum('ii', a)`` is equivalent 

2009 to :py:func:`np.trace(a) <numpy.trace>`. 

2010 

2011 In *implicit mode*, the chosen subscripts are important 

2012 since the axes of the output are reordered alphabetically. This 

2013 means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while 

2014 ``np.einsum('ji', a)`` takes its transpose. Additionally, 

2015 ``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while, 

2016 ``np.einsum('ij,jh', a, b)`` returns the transpose of the 

2017 multiplication since subscript 'h' precedes subscript 'i'. 

2018 

2019 In *explicit mode* the output can be directly controlled by 

2020 specifying output subscript labels. This requires the 

2021 identifier '->' as well as the list of output subscript labels. 

2022 This feature increases the flexibility of the function since 

2023 summing can be disabled or forced when required. The call 

2024 ``np.einsum('i->', a)`` is like :py:func:`np.sum(a) <numpy.sum>` 

2025 if ``a`` is a 1-D array, and ``np.einsum('ii->i', a)`` 

2026 is like :py:func:`np.diag(a) <numpy.diag>` if ``a`` is a square 2-D array. 

2027 The difference is that `einsum` does not allow broadcasting by default. 

2028 Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the 

2029 order of the output subscript labels and therefore returns matrix 

2030 multiplication, unlike the example above in implicit mode. 

2031 

2032 To enable and control broadcasting, use an ellipsis. Default 

2033 NumPy-style broadcasting is done by adding an ellipsis 

2034 to the left of each term, like ``np.einsum('...ii->...i', a)``. 

2035 ``np.einsum('...i->...', a)`` is like  

2036 :py:func:`np.sum(a, axis=-1) <numpy.sum>` for array ``a`` of any shape. 

2037 To take the trace along the first and last axes, 

2038 you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix 

2039 product with the left-most indices instead of rightmost, one can do 

2040 ``np.einsum('ij...,jk...->ik...', a, b)``. 

2041 

2042 When there is only one operand, no axes are summed, and no output 

2043 parameter is provided, a view into the operand is returned instead 

2044 of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)`` 

2045 produces a view (changed in version 1.10.0). 

2046 

2047 `einsum` also provides an alternative way to provide the subscripts 

2048 and operands as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``. 

2049 If the output shape is not provided in this format `einsum` will be 

2050 calculated in implicit mode, otherwise it will be performed explicitly. 

2051 The examples below have corresponding `einsum` calls with the two 

2052 parameter methods. 

2053 

2054 .. versionadded:: 1.10.0 

2055 

2056 Views returned from einsum are now writeable whenever the input array 

2057 is writeable. For example, ``np.einsum('ijk...->kji...', a)`` will now 

2058 have the same effect as :py:func:`np.swapaxes(a, 0, 2) <numpy.swapaxes>` 

2059 and ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal 

2060 of a 2D array. 

2061 

2062 Examples 

2063 -------- 

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

2065 >>> b = np.arange(5) 

2066 >>> c = np.arange(6).reshape(2,3) 

2067 

2068 Trace of a matrix: 

2069 

2070 >>> np.einsum('ii', a) 

2071 60 

2072 >>> np.einsum(a, [0,0]) 

2073 60 

2074 >>> np.trace(a) 

2075 60 

2076 

2077 Extract the diagonal (requires explicit form): 

2078 

2079 >>> np.einsum('ii->i', a) 

2080 array([ 0, 6, 12, 18, 24]) 

2081 >>> np.einsum(a, [0,0], [0]) 

2082 array([ 0, 6, 12, 18, 24]) 

2083 >>> np.diag(a) 

2084 array([ 0, 6, 12, 18, 24]) 

2085 

2086 Sum over an axis (requires explicit form): 

2087 

2088 >>> np.einsum('ij->i', a) 

2089 array([ 10, 35, 60, 85, 110]) 

2090 >>> np.einsum(a, [0,1], [0]) 

2091 array([ 10, 35, 60, 85, 110]) 

2092 >>> np.sum(a, axis=1) 

2093 array([ 10, 35, 60, 85, 110]) 

2094 

2095 For higher dimensional arrays summing a single axis can be done with ellipsis: 

2096 

2097 >>> np.einsum('...j->...', a) 

2098 array([ 10, 35, 60, 85, 110]) 

2099 >>> np.einsum(a, [Ellipsis,1], [Ellipsis]) 

2100 array([ 10, 35, 60, 85, 110]) 

2101 

2102 Compute a matrix transpose, or reorder any number of axes: 

2103 

2104 >>> np.einsum('ji', c) 

2105 array([[0, 3], 

2106 [1, 4], 

2107 [2, 5]]) 

2108 >>> np.einsum('ij->ji', c) 

2109 array([[0, 3], 

2110 [1, 4], 

2111 [2, 5]]) 

2112 >>> np.einsum(c, [1,0]) 

2113 array([[0, 3], 

2114 [1, 4], 

2115 [2, 5]]) 

2116 >>> np.transpose(c) 

2117 array([[0, 3], 

2118 [1, 4], 

2119 [2, 5]]) 

2120 

2121 Vector inner products: 

2122 

2123 >>> np.einsum('i,i', b, b) 

2124 30 

2125 >>> np.einsum(b, [0], b, [0]) 

2126 30 

2127 >>> np.inner(b,b) 

2128 30 

2129 

2130 Matrix vector multiplication: 

2131 

2132 >>> np.einsum('ij,j', a, b) 

2133 array([ 30, 80, 130, 180, 230]) 

2134 >>> np.einsum(a, [0,1], b, [1]) 

2135 array([ 30, 80, 130, 180, 230]) 

2136 >>> np.dot(a, b) 

2137 array([ 30, 80, 130, 180, 230]) 

2138 >>> np.einsum('...j,j', a, b) 

2139 array([ 30, 80, 130, 180, 230]) 

2140 

2141 Broadcasting and scalar multiplication: 

2142 

2143 >>> np.einsum('..., ...', 3, c) 

2144 array([[ 0, 3, 6], 

2145 [ 9, 12, 15]]) 

2146 >>> np.einsum(',ij', 3, c) 

2147 array([[ 0, 3, 6], 

2148 [ 9, 12, 15]]) 

2149 >>> np.einsum(3, [Ellipsis], c, [Ellipsis]) 

2150 array([[ 0, 3, 6], 

2151 [ 9, 12, 15]]) 

2152 >>> np.multiply(3, c) 

2153 array([[ 0, 3, 6], 

2154 [ 9, 12, 15]]) 

2155 

2156 Vector outer product: 

2157 

2158 >>> np.einsum('i,j', np.arange(2)+1, b) 

2159 array([[0, 1, 2, 3, 4], 

2160 [0, 2, 4, 6, 8]]) 

2161 >>> np.einsum(np.arange(2)+1, [0], b, [1]) 

2162 array([[0, 1, 2, 3, 4], 

2163 [0, 2, 4, 6, 8]]) 

2164 >>> np.outer(np.arange(2)+1, b) 

2165 array([[0, 1, 2, 3, 4], 

2166 [0, 2, 4, 6, 8]]) 

2167 

2168 Tensor contraction: 

2169 

2170 >>> a = np.arange(60.).reshape(3,4,5) 

2171 >>> b = np.arange(24.).reshape(4,3,2) 

2172 >>> np.einsum('ijk,jil->kl', a, b) 

2173 array([[ 4400., 4730.], 

2174 [ 4532., 4874.], 

2175 [ 4664., 5018.], 

2176 [ 4796., 5162.], 

2177 [ 4928., 5306.]]) 

2178 >>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3]) 

2179 array([[ 4400., 4730.], 

2180 [ 4532., 4874.], 

2181 [ 4664., 5018.], 

2182 [ 4796., 5162.], 

2183 [ 4928., 5306.]]) 

2184 >>> np.tensordot(a,b, axes=([1,0],[0,1])) 

2185 array([[ 4400., 4730.], 

2186 [ 4532., 4874.], 

2187 [ 4664., 5018.], 

2188 [ 4796., 5162.], 

2189 [ 4928., 5306.]]) 

2190 

2191 Writeable returned arrays (since version 1.10.0): 

2192 

2193 >>> a = np.zeros((3, 3)) 

2194 >>> np.einsum('ii->i', a)[:] = 1 

2195 >>> a 

2196 array([[ 1., 0., 0.], 

2197 [ 0., 1., 0.], 

2198 [ 0., 0., 1.]]) 

2199 

2200 Example of ellipsis use: 

2201 

2202 >>> a = np.arange(6).reshape((3,2)) 

2203 >>> b = np.arange(12).reshape((4,3)) 

2204 >>> np.einsum('ki,jk->ij', a, b) 

2205 array([[10, 28, 46, 64], 

2206 [13, 40, 67, 94]]) 

2207 >>> np.einsum('ki,...k->i...', a, b) 

2208 array([[10, 28, 46, 64], 

2209 [13, 40, 67, 94]]) 

2210 >>> np.einsum('k...,jk', a, b) 

2211 array([[10, 28, 46, 64], 

2212 [13, 40, 67, 94]]) 

2213 

2214 """) 

2215 

2216 

2217############################################################################## 

2218# 

2219# Documentation for ndarray attributes and methods 

2220# 

2221############################################################################## 

2222 

2223 

2224############################################################################## 

2225# 

2226# ndarray object 

2227# 

2228############################################################################## 

2229 

2230 

2231add_newdoc('numpy._core.multiarray', 'ndarray', 

2232 """ 

2233 ndarray(shape, dtype=float, buffer=None, offset=0, 

2234 strides=None, order=None) 

2235 

2236 An array object represents a multidimensional, homogeneous array 

2237 of fixed-size items. An associated data-type object describes the 

2238 format of each element in the array (its byte-order, how many bytes it 

2239 occupies in memory, whether it is an integer, a floating point number, 

2240 or something else, etc.) 

2241 

2242 Arrays should be constructed using `array`, `zeros` or `empty` (refer 

2243 to the See Also section below). The parameters given here refer to 

2244 a low-level method (`ndarray(...)`) for instantiating an array. 

2245 

2246 For more information, refer to the `numpy` module and examine the 

2247 methods and attributes of an array. 

2248 

2249 Parameters 

2250 ---------- 

2251 (for the __new__ method; see Notes below) 

2252 

2253 shape : tuple of ints 

2254 Shape of created array. 

2255 dtype : data-type, optional 

2256 Any object that can be interpreted as a numpy data type. 

2257 buffer : object exposing buffer interface, optional 

2258 Used to fill the array with data. 

2259 offset : int, optional 

2260 Offset of array data in buffer. 

2261 strides : tuple of ints, optional 

2262 Strides of data in memory. 

2263 order : {'C', 'F'}, optional 

2264 Row-major (C-style) or column-major (Fortran-style) order. 

2265 

2266 Attributes 

2267 ---------- 

2268 T : ndarray 

2269 Transpose of the array. 

2270 data : buffer 

2271 The array's elements, in memory. 

2272 dtype : dtype object 

2273 Describes the format of the elements in the array. 

2274 flags : dict 

2275 Dictionary containing information related to memory use, e.g., 

2276 'C_CONTIGUOUS', 'OWNDATA', 'WRITEABLE', etc. 

2277 flat : numpy.flatiter object 

2278 Flattened version of the array as an iterator. The iterator 

2279 allows assignments, e.g., ``x.flat = 3`` (See `ndarray.flat` for 

2280 assignment examples; TODO). 

2281 imag : ndarray 

2282 Imaginary part of the array. 

2283 real : ndarray 

2284 Real part of the array. 

2285 size : int 

2286 Number of elements in the array. 

2287 itemsize : int 

2288 The memory use of each array element in bytes. 

2289 nbytes : int 

2290 The total number of bytes required to store the array data, 

2291 i.e., ``itemsize * size``. 

2292 ndim : int 

2293 The array's number of dimensions. 

2294 shape : tuple of ints 

2295 Shape of the array. 

2296 strides : tuple of ints 

2297 The step-size required to move from one element to the next in 

2298 memory. For example, a contiguous ``(3, 4)`` array of type 

2299 ``int16`` in C-order has strides ``(8, 2)``. This implies that 

2300 to move from element to element in memory requires jumps of 2 bytes. 

2301 To move from row-to-row, one needs to jump 8 bytes at a time 

2302 (``2 * 4``). 

2303 ctypes : ctypes object 

2304 Class containing properties of the array needed for interaction 

2305 with ctypes. 

2306 base : ndarray 

2307 If the array is a view into another array, that array is its `base` 

2308 (unless that array is also a view). The `base` array is where the 

2309 array data is actually stored. 

2310 

2311 See Also 

2312 -------- 

2313 array : Construct an array. 

2314 zeros : Create an array, each element of which is zero. 

2315 empty : Create an array, but leave its allocated memory unchanged (i.e., 

2316 it contains "garbage"). 

2317 dtype : Create a data-type. 

2318 numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>` 

2319 w.r.t. its `dtype.type <numpy.dtype.type>`. 

2320 

2321 Notes 

2322 ----- 

2323 There are two modes of creating an array using ``__new__``: 

2324 

2325 1. If `buffer` is None, then only `shape`, `dtype`, and `order` 

2326 are used. 

2327 2. If `buffer` is an object exposing the buffer interface, then 

2328 all keywords are interpreted. 

2329 

2330 No ``__init__`` method is needed because the array is fully initialized 

2331 after the ``__new__`` method. 

2332 

2333 Examples 

2334 -------- 

2335 These examples illustrate the low-level `ndarray` constructor. Refer 

2336 to the `See Also` section above for easier ways of constructing an 

2337 ndarray. 

2338 

2339 First mode, `buffer` is None: 

2340 

2341 >>> np.ndarray(shape=(2,2), dtype=float, order='F') 

2342 array([[0.0e+000, 0.0e+000], # random 

2343 [ nan, 2.5e-323]]) 

2344 

2345 Second mode: 

2346 

2347 >>> np.ndarray((2,), buffer=np.array([1,2,3]), 

2348 ... offset=np.int_().itemsize, 

2349 ... dtype=int) # offset = 1*itemsize, i.e. skip first element 

2350 array([2, 3]) 

2351 

2352 """) 

2353 

2354 

2355############################################################################## 

2356# 

2357# ndarray attributes 

2358# 

2359############################################################################## 

2360 

2361 

2362add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_interface__', 

2363 """Array protocol: Python side.""")) 

2364 

2365 

2366add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_priority__', 

2367 """Array priority.""")) 

2368 

2369 

2370add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_struct__', 

2371 """Array protocol: C-struct side.""")) 

2372 

2373add_newdoc('numpy._core.multiarray', 'ndarray', ('__dlpack__', 

2374 """a.__dlpack__(*, stream=None) 

2375 

2376 DLPack Protocol: Part of the Array API.""")) 

2377 

2378add_newdoc('numpy._core.multiarray', 'ndarray', ('__dlpack_device__', 

2379 """a.__dlpack_device__() 

2380 

2381 DLPack Protocol: Part of the Array API.""")) 

2382 

2383add_newdoc('numpy._core.multiarray', 'ndarray', ('base', 

2384 """ 

2385 Base object if memory is from some other object. 

2386 

2387 Examples 

2388 -------- 

2389 The base of an array that owns its memory is None: 

2390 

2391 >>> x = np.array([1,2,3,4]) 

2392 >>> x.base is None 

2393 True 

2394 

2395 Slicing creates a view, whose memory is shared with x: 

2396 

2397 >>> y = x[2:] 

2398 >>> y.base is x 

2399 True 

2400 

2401 """)) 

2402 

2403 

2404add_newdoc('numpy._core.multiarray', 'ndarray', ('ctypes', 

2405 """ 

2406 An object to simplify the interaction of the array with the ctypes 

2407 module. 

2408 

2409 This attribute creates an object that makes it easier to use arrays 

2410 when calling shared libraries with the ctypes module. The returned 

2411 object has, among others, data, shape, and strides attributes (see 

2412 Notes below) which themselves return ctypes objects that can be used 

2413 as arguments to a shared library. 

2414 

2415 Parameters 

2416 ---------- 

2417 None 

2418 

2419 Returns 

2420 ------- 

2421 c : Python object 

2422 Possessing attributes data, shape, strides, etc. 

2423 

2424 See Also 

2425 -------- 

2426 numpy.ctypeslib 

2427 

2428 Notes 

2429 ----- 

2430 Below are the public attributes of this object which were documented 

2431 in "Guide to NumPy" (we have omitted undocumented public attributes, 

2432 as well as documented private attributes): 

2433 

2434 .. autoattribute:: numpy._core._internal._ctypes.data 

2435 :noindex: 

2436 

2437 .. autoattribute:: numpy._core._internal._ctypes.shape 

2438 :noindex: 

2439 

2440 .. autoattribute:: numpy._core._internal._ctypes.strides 

2441 :noindex: 

2442 

2443 .. automethod:: numpy._core._internal._ctypes.data_as 

2444 :noindex: 

2445 

2446 .. automethod:: numpy._core._internal._ctypes.shape_as 

2447 :noindex: 

2448 

2449 .. automethod:: numpy._core._internal._ctypes.strides_as 

2450 :noindex: 

2451 

2452 If the ctypes module is not available, then the ctypes attribute 

2453 of array objects still returns something useful, but ctypes objects 

2454 are not returned and errors may be raised instead. In particular, 

2455 the object will still have the ``as_parameter`` attribute which will 

2456 return an integer equal to the data attribute. 

2457 

2458 Examples 

2459 -------- 

2460 >>> import ctypes 

2461 >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32) 

2462 >>> x 

2463 array([[0, 1], 

2464 [2, 3]], dtype=int32) 

2465 >>> x.ctypes.data 

2466 31962608 # may vary 

2467 >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)) 

2468 <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary 

2469 >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents 

2470 c_uint(0) 

2471 >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents 

2472 c_ulong(4294967296) 

2473 >>> x.ctypes.shape 

2474 <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary 

2475 >>> x.ctypes.strides 

2476 <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary 

2477 

2478 """)) 

2479 

2480 

2481add_newdoc('numpy._core.multiarray', 'ndarray', ('data', 

2482 """Python buffer object pointing to the start of the array's data.""")) 

2483 

2484 

2485add_newdoc('numpy._core.multiarray', 'ndarray', ('dtype', 

2486 """ 

2487 Data-type of the array's elements. 

2488 

2489 .. warning:: 

2490 

2491 Setting ``arr.dtype`` is discouraged and may be deprecated in the 

2492 future. Setting will replace the ``dtype`` without modifying the 

2493 memory (see also `ndarray.view` and `ndarray.astype`). 

2494 

2495 Parameters 

2496 ---------- 

2497 None 

2498 

2499 Returns 

2500 ------- 

2501 d : numpy dtype object 

2502 

2503 See Also 

2504 -------- 

2505 ndarray.astype : Cast the values contained in the array to a new data-type. 

2506 ndarray.view : Create a view of the same data but a different data-type. 

2507 numpy.dtype 

2508 

2509 Examples 

2510 -------- 

2511 >>> x 

2512 array([[0, 1], 

2513 [2, 3]]) 

2514 >>> x.dtype 

2515 dtype('int32') 

2516 >>> type(x.dtype) 

2517 <type 'numpy.dtype'> 

2518 

2519 """)) 

2520 

2521 

2522add_newdoc('numpy._core.multiarray', 'ndarray', ('imag', 

2523 """ 

2524 The imaginary part of the array. 

2525 

2526 Examples 

2527 -------- 

2528 >>> x = np.sqrt([1+0j, 0+1j]) 

2529 >>> x.imag 

2530 array([ 0. , 0.70710678]) 

2531 >>> x.imag.dtype 

2532 dtype('float64') 

2533 

2534 """)) 

2535 

2536 

2537add_newdoc('numpy._core.multiarray', 'ndarray', ('itemsize', 

2538 """ 

2539 Length of one array element in bytes. 

2540 

2541 Examples 

2542 -------- 

2543 >>> x = np.array([1,2,3], dtype=np.float64) 

2544 >>> x.itemsize 

2545 8 

2546 >>> x = np.array([1,2,3], dtype=np.complex128) 

2547 >>> x.itemsize 

2548 16 

2549 

2550 """)) 

2551 

2552 

2553add_newdoc('numpy._core.multiarray', 'ndarray', ('flags', 

2554 """ 

2555 Information about the memory layout of the array. 

2556 

2557 Attributes 

2558 ---------- 

2559 C_CONTIGUOUS (C) 

2560 The data is in a single, C-style contiguous segment. 

2561 F_CONTIGUOUS (F) 

2562 The data is in a single, Fortran-style contiguous segment. 

2563 OWNDATA (O) 

2564 The array owns the memory it uses or borrows it from another object. 

2565 WRITEABLE (W) 

2566 The data area can be written to. Setting this to False locks 

2567 the data, making it read-only. A view (slice, etc.) inherits WRITEABLE 

2568 from its base array at creation time, but a view of a writeable 

2569 array may be subsequently locked while the base array remains writeable. 

2570 (The opposite is not true, in that a view of a locked array may not 

2571 be made writeable. However, currently, locking a base object does not 

2572 lock any views that already reference it, so under that circumstance it 

2573 is possible to alter the contents of a locked array via a previously 

2574 created writeable view onto it.) Attempting to change a non-writeable 

2575 array raises a RuntimeError exception. 

2576 ALIGNED (A) 

2577 The data and all elements are aligned appropriately for the hardware. 

2578 WRITEBACKIFCOPY (X) 

2579 This array is a copy of some other array. The C-API function 

2580 PyArray_ResolveWritebackIfCopy must be called before deallocating 

2581 to the base array will be updated with the contents of this array. 

2582 FNC 

2583 F_CONTIGUOUS and not C_CONTIGUOUS. 

2584 FORC 

2585 F_CONTIGUOUS or C_CONTIGUOUS (one-segment test). 

2586 BEHAVED (B) 

2587 ALIGNED and WRITEABLE. 

2588 CARRAY (CA) 

2589 BEHAVED and C_CONTIGUOUS. 

2590 FARRAY (FA) 

2591 BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS. 

2592 

2593 Notes 

2594 ----- 

2595 The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``), 

2596 or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag 

2597 names are only supported in dictionary access. 

2598 

2599 Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be 

2600 changed by the user, via direct assignment to the attribute or dictionary 

2601 entry, or by calling `ndarray.setflags`. 

2602 

2603 The array flags cannot be set arbitrarily: 

2604 

2605 - WRITEBACKIFCOPY can only be set ``False``. 

2606 - ALIGNED can only be set ``True`` if the data is truly aligned. 

2607 - WRITEABLE can only be set ``True`` if the array owns its own memory 

2608 or the ultimate owner of the memory exposes a writeable buffer 

2609 interface or is a string. 

2610 

2611 Arrays can be both C-style and Fortran-style contiguous simultaneously. 

2612 This is clear for 1-dimensional arrays, but can also be true for higher 

2613 dimensional arrays. 

2614 

2615 Even for contiguous arrays a stride for a given dimension 

2616 ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1`` 

2617 or the array has no elements. 

2618 It does *not* generally hold that ``self.strides[-1] == self.itemsize`` 

2619 for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for 

2620 Fortran-style contiguous arrays is true. 

2621 """)) 

2622 

2623 

2624add_newdoc('numpy._core.multiarray', 'ndarray', ('flat', 

2625 """ 

2626 A 1-D iterator over the array. 

2627 

2628 This is a `numpy.flatiter` instance, which acts similarly to, but is not 

2629 a subclass of, Python's built-in iterator object. 

2630 

2631 See Also 

2632 -------- 

2633 flatten : Return a copy of the array collapsed into one dimension. 

2634 

2635 flatiter 

2636 

2637 Examples 

2638 -------- 

2639 >>> x = np.arange(1, 7).reshape(2, 3) 

2640 >>> x 

2641 array([[1, 2, 3], 

2642 [4, 5, 6]]) 

2643 >>> x.flat[3] 

2644 4 

2645 >>> x.T 

2646 array([[1, 4], 

2647 [2, 5], 

2648 [3, 6]]) 

2649 >>> x.T.flat[3] 

2650 5 

2651 >>> type(x.flat) 

2652 <class 'numpy.flatiter'> 

2653 

2654 An assignment example: 

2655 

2656 >>> x.flat = 3; x 

2657 array([[3, 3, 3], 

2658 [3, 3, 3]]) 

2659 >>> x.flat[[1,4]] = 1; x 

2660 array([[3, 1, 3], 

2661 [3, 1, 3]]) 

2662 

2663 """)) 

2664 

2665 

2666add_newdoc('numpy._core.multiarray', 'ndarray', ('nbytes', 

2667 """ 

2668 Total bytes consumed by the elements of the array. 

2669 

2670 Notes 

2671 ----- 

2672 Does not include memory consumed by non-element attributes of the 

2673 array object. 

2674 

2675 See Also 

2676 -------- 

2677 sys.getsizeof 

2678 Memory consumed by the object itself without parents in case view. 

2679 This does include memory consumed by non-element attributes. 

2680 

2681 Examples 

2682 -------- 

2683 >>> x = np.zeros((3,5,2), dtype=np.complex128) 

2684 >>> x.nbytes 

2685 480 

2686 >>> np.prod(x.shape) * x.itemsize 

2687 480 

2688 

2689 """)) 

2690 

2691 

2692add_newdoc('numpy._core.multiarray', 'ndarray', ('ndim', 

2693 """ 

2694 Number of array dimensions. 

2695 

2696 Examples 

2697 -------- 

2698 >>> x = np.array([1, 2, 3]) 

2699 >>> x.ndim 

2700 1 

2701 >>> y = np.zeros((2, 3, 4)) 

2702 >>> y.ndim 

2703 3 

2704 

2705 """)) 

2706 

2707 

2708add_newdoc('numpy._core.multiarray', 'ndarray', ('real', 

2709 """ 

2710 The real part of the array. 

2711 

2712 Examples 

2713 -------- 

2714 >>> x = np.sqrt([1+0j, 0+1j]) 

2715 >>> x.real 

2716 array([ 1. , 0.70710678]) 

2717 >>> x.real.dtype 

2718 dtype('float64') 

2719 

2720 See Also 

2721 -------- 

2722 numpy.real : equivalent function 

2723 

2724 """)) 

2725 

2726 

2727add_newdoc('numpy._core.multiarray', 'ndarray', ('shape', 

2728 """ 

2729 Tuple of array dimensions. 

2730 

2731 The shape property is usually used to get the current shape of an array, 

2732 but may also be used to reshape the array in-place by assigning a tuple of 

2733 array dimensions to it. As with `numpy.reshape`, one of the new shape 

2734 dimensions can be -1, in which case its value is inferred from the size of 

2735 the array and the remaining dimensions. Reshaping an array in-place will 

2736 fail if a copy is required. 

2737 

2738 .. warning:: 

2739 

2740 Setting ``arr.shape`` is discouraged and may be deprecated in the 

2741 future. Using `ndarray.reshape` is the preferred approach. 

2742 

2743 Examples 

2744 -------- 

2745 >>> x = np.array([1, 2, 3, 4]) 

2746 >>> x.shape 

2747 (4,) 

2748 >>> y = np.zeros((2, 3, 4)) 

2749 >>> y.shape 

2750 (2, 3, 4) 

2751 >>> y.shape = (3, 8) 

2752 >>> y 

2753 array([[ 0., 0., 0., 0., 0., 0., 0., 0.], 

2754 [ 0., 0., 0., 0., 0., 0., 0., 0.], 

2755 [ 0., 0., 0., 0., 0., 0., 0., 0.]]) 

2756 >>> y.shape = (3, 6) 

2757 Traceback (most recent call last): 

2758 File "<stdin>", line 1, in <module> 

2759 ValueError: total size of new array must be unchanged 

2760 >>> np.zeros((4,2))[::2].shape = (-1,) 

2761 Traceback (most recent call last): 

2762 File "<stdin>", line 1, in <module> 

2763 AttributeError: Incompatible shape for in-place modification. Use 

2764 `.reshape()` to make a copy with the desired shape. 

2765 

2766 See Also 

2767 -------- 

2768 numpy.shape : Equivalent getter function. 

2769 numpy.reshape : Function similar to setting ``shape``. 

2770 ndarray.reshape : Method similar to setting ``shape``. 

2771 

2772 """)) 

2773 

2774 

2775add_newdoc('numpy._core.multiarray', 'ndarray', ('size', 

2776 """ 

2777 Number of elements in the array. 

2778 

2779 Equal to ``np.prod(a.shape)``, i.e., the product of the array's 

2780 dimensions. 

2781 

2782 Notes 

2783 ----- 

2784 `a.size` returns a standard arbitrary precision Python integer. This 

2785 may not be the case with other methods of obtaining the same value 

2786 (like the suggested ``np.prod(a.shape)``, which returns an instance 

2787 of ``np.int_``), and may be relevant if the value is used further in 

2788 calculations that may overflow a fixed size integer type. 

2789 

2790 Examples 

2791 -------- 

2792 >>> x = np.zeros((3, 5, 2), dtype=np.complex128) 

2793 >>> x.size 

2794 30 

2795 >>> np.prod(x.shape) 

2796 30 

2797 

2798 """)) 

2799 

2800 

2801add_newdoc('numpy._core.multiarray', 'ndarray', ('strides', 

2802 """ 

2803 Tuple of bytes to step in each dimension when traversing an array. 

2804 

2805 The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a` 

2806 is:: 

2807 

2808 offset = sum(np.array(i) * a.strides) 

2809 

2810 A more detailed explanation of strides can be found in 

2811 :ref:`arrays.ndarray`. 

2812 

2813 .. warning:: 

2814 

2815 Setting ``arr.strides`` is discouraged and may be deprecated in the 

2816 future. `numpy.lib.stride_tricks.as_strided` should be preferred 

2817 to create a new view of the same data in a safer way. 

2818 

2819 Notes 

2820 ----- 

2821 Imagine an array of 32-bit integers (each 4 bytes):: 

2822 

2823 x = np.array([[0, 1, 2, 3, 4], 

2824 [5, 6, 7, 8, 9]], dtype=np.int32) 

2825 

2826 This array is stored in memory as 40 bytes, one after the other 

2827 (known as a contiguous block of memory). The strides of an array tell 

2828 us how many bytes we have to skip in memory to move to the next position 

2829 along a certain axis. For example, we have to skip 4 bytes (1 value) to 

2830 move to the next column, but 20 bytes (5 values) to get to the same 

2831 position in the next row. As such, the strides for the array `x` will be 

2832 ``(20, 4)``. 

2833 

2834 See Also 

2835 -------- 

2836 numpy.lib.stride_tricks.as_strided 

2837 

2838 Examples 

2839 -------- 

2840 >>> y = np.reshape(np.arange(2*3*4), (2,3,4)) 

2841 >>> y 

2842 array([[[ 0, 1, 2, 3], 

2843 [ 4, 5, 6, 7], 

2844 [ 8, 9, 10, 11]], 

2845 [[12, 13, 14, 15], 

2846 [16, 17, 18, 19], 

2847 [20, 21, 22, 23]]]) 

2848 >>> y.strides 

2849 (48, 16, 4) 

2850 >>> y[1,1,1] 

2851 17 

2852 >>> offset=sum(y.strides * np.array((1,1,1))) 

2853 >>> offset/y.itemsize 

2854 17 

2855 

2856 >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0) 

2857 >>> x.strides 

2858 (32, 4, 224, 1344) 

2859 >>> i = np.array([3,5,2,2]) 

2860 >>> offset = sum(i * x.strides) 

2861 >>> x[3,5,2,2] 

2862 813 

2863 >>> offset / x.itemsize 

2864 813 

2865 

2866 """)) 

2867 

2868 

2869add_newdoc('numpy._core.multiarray', 'ndarray', ('T', 

2870 """ 

2871 View of the transposed array. 

2872 

2873 Same as ``self.transpose()``. 

2874 

2875 Examples 

2876 -------- 

2877 >>> a = np.array([[1, 2], [3, 4]]) 

2878 >>> a 

2879 array([[1, 2], 

2880 [3, 4]]) 

2881 >>> a.T 

2882 array([[1, 3], 

2883 [2, 4]]) 

2884 

2885 >>> a = np.array([1, 2, 3, 4]) 

2886 >>> a 

2887 array([1, 2, 3, 4]) 

2888 >>> a.T 

2889 array([1, 2, 3, 4]) 

2890 

2891 See Also 

2892 -------- 

2893 transpose 

2894 

2895 """)) 

2896 

2897 

2898add_newdoc('numpy._core.multiarray', 'ndarray', ('mT', 

2899 """ 

2900 View of the matrix transposed array. 

2901 

2902 The matrix transpose is the transpose of the last two dimensions, even 

2903 if the array is of higher dimension. 

2904 

2905 .. versionadded:: 2.0 

2906 

2907 Raises 

2908 ------ 

2909 ValueError 

2910 If the array is of dimension less than 2. 

2911 

2912 Examples 

2913 -------- 

2914 >>> a = np.array([[1, 2], [3, 4]]) 

2915 >>> a 

2916 array([[1, 2], 

2917 [3, 4]]) 

2918 >>> a.mT 

2919 array([[1, 3], 

2920 [2, 4]]) 

2921 

2922 >>> a = np.arange(8).reshape((2, 2, 2)) 

2923 >>> a 

2924 array([[[0, 1], 

2925 [2, 3]], 

2926 <BLANKLINE> 

2927 [[4, 5], 

2928 [6, 7]]]) 

2929 >>> a.mT 

2930 array([[[0, 2], 

2931 [1, 3]], 

2932 <BLANKLINE> 

2933 [[4, 6], 

2934 [5, 7]]]) 

2935 

2936 """)) 

2937############################################################################## 

2938# 

2939# ndarray methods 

2940# 

2941############################################################################## 

2942 

2943 

2944add_newdoc('numpy._core.multiarray', 'ndarray', ('__array__', 

2945 """ 

2946 a.__array__([dtype], /, *, copy=None) 

2947 

2948 For ``dtype`` parameter it returns either a new reference to self if 

2949 ``dtype`` is not given or a new array of provided data type if ``dtype`` 

2950 is different from the current data type of the array. 

2951 For ``copy`` parameter it returns a new reference to self if 

2952 ``copy=False`` or ``copy=None`` and copying isn't enforced by ``dtype`` 

2953 parameter. The method returns a new array for ``copy=True``, regardless of 

2954 ``dtype`` parameter. 

2955 

2956 """)) 

2957 

2958 

2959add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_finalize__', 

2960 """ 

2961 a.__array_finalize__(obj, /) 

2962 

2963 Present so subclasses can call super. Does nothing. 

2964 

2965 """)) 

2966 

2967 

2968add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_wrap__', 

2969 """ 

2970 a.__array_wrap__(array[, context], /) 

2971 

2972 Returns a view of `array` with the same type as self. 

2973 

2974 """)) 

2975 

2976 

2977add_newdoc('numpy._core.multiarray', 'ndarray', ('__copy__', 

2978 """ 

2979 a.__copy__() 

2980 

2981 Used if :func:`copy.copy` is called on an array. Returns a copy of the array. 

2982 

2983 Equivalent to ``a.copy(order='K')``. 

2984 

2985 """)) 

2986 

2987 

2988add_newdoc('numpy._core.multiarray', 'ndarray', ('__class_getitem__', 

2989 """ 

2990 a.__class_getitem__(item, /) 

2991 

2992 Return a parametrized wrapper around the `~numpy.ndarray` type. 

2993 

2994 .. versionadded:: 1.22 

2995 

2996 Returns 

2997 ------- 

2998 alias : types.GenericAlias 

2999 A parametrized `~numpy.ndarray` type. 

3000 

3001 Examples 

3002 -------- 

3003 >>> from typing import Any 

3004 >>> import numpy as np 

3005 

3006 >>> np.ndarray[Any, np.dtype[Any]] 

3007 numpy.ndarray[typing.Any, numpy.dtype[typing.Any]] 

3008 

3009 See Also 

3010 -------- 

3011 :pep:`585` : Type hinting generics in standard collections. 

3012 numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>` 

3013 w.r.t. its `dtype.type <numpy.dtype.type>`. 

3014 

3015 """)) 

3016 

3017 

3018add_newdoc('numpy._core.multiarray', 'ndarray', ('__deepcopy__', 

3019 """ 

3020 a.__deepcopy__(memo, /) 

3021 

3022 Used if :func:`copy.deepcopy` is called on an array. 

3023 

3024 """)) 

3025 

3026 

3027add_newdoc('numpy._core.multiarray', 'ndarray', ('__reduce__', 

3028 """ 

3029 a.__reduce__() 

3030 

3031 For pickling. 

3032 

3033 """)) 

3034 

3035 

3036add_newdoc('numpy._core.multiarray', 'ndarray', ('__setstate__', 

3037 """ 

3038 a.__setstate__(state, /) 

3039 

3040 For unpickling. 

3041 

3042 The `state` argument must be a sequence that contains the following 

3043 elements: 

3044 

3045 Parameters 

3046 ---------- 

3047 version : int 

3048 optional pickle version. If omitted defaults to 0. 

3049 shape : tuple 

3050 dtype : data-type 

3051 isFortran : bool 

3052 rawdata : string or list 

3053 a binary string with the data (or a list if 'a' is an object array) 

3054 

3055 """)) 

3056 

3057 

3058add_newdoc('numpy._core.multiarray', 'ndarray', ('all', 

3059 """ 

3060 a.all(axis=None, out=None, keepdims=False, *, where=True) 

3061 

3062 Returns True if all elements evaluate to True. 

3063 

3064 Refer to `numpy.all` for full documentation. 

3065 

3066 See Also 

3067 -------- 

3068 numpy.all : equivalent function 

3069 

3070 """)) 

3071 

3072 

3073add_newdoc('numpy._core.multiarray', 'ndarray', ('any', 

3074 """ 

3075 a.any(axis=None, out=None, keepdims=False, *, where=True) 

3076 

3077 Returns True if any of the elements of `a` evaluate to True. 

3078 

3079 Refer to `numpy.any` for full documentation. 

3080 

3081 See Also 

3082 -------- 

3083 numpy.any : equivalent function 

3084 

3085 """)) 

3086 

3087 

3088add_newdoc('numpy._core.multiarray', 'ndarray', ('argmax', 

3089 """ 

3090 a.argmax(axis=None, out=None, *, keepdims=False) 

3091 

3092 Return indices of the maximum values along the given axis. 

3093 

3094 Refer to `numpy.argmax` for full documentation. 

3095 

3096 See Also 

3097 -------- 

3098 numpy.argmax : equivalent function 

3099 

3100 """)) 

3101 

3102 

3103add_newdoc('numpy._core.multiarray', 'ndarray', ('argmin', 

3104 """ 

3105 a.argmin(axis=None, out=None, *, keepdims=False) 

3106 

3107 Return indices of the minimum values along the given axis. 

3108 

3109 Refer to `numpy.argmin` for detailed documentation. 

3110 

3111 See Also 

3112 -------- 

3113 numpy.argmin : equivalent function 

3114 

3115 """)) 

3116 

3117 

3118add_newdoc('numpy._core.multiarray', 'ndarray', ('argsort', 

3119 """ 

3120 a.argsort(axis=-1, kind=None, order=None) 

3121 

3122 Returns the indices that would sort this array. 

3123 

3124 Refer to `numpy.argsort` for full documentation. 

3125 

3126 See Also 

3127 -------- 

3128 numpy.argsort : equivalent function 

3129 

3130 """)) 

3131 

3132 

3133add_newdoc('numpy._core.multiarray', 'ndarray', ('argpartition', 

3134 """ 

3135 a.argpartition(kth, axis=-1, kind='introselect', order=None) 

3136 

3137 Returns the indices that would partition this array. 

3138 

3139 Refer to `numpy.argpartition` for full documentation. 

3140 

3141 .. versionadded:: 1.8.0 

3142 

3143 See Also 

3144 -------- 

3145 numpy.argpartition : equivalent function 

3146 

3147 """)) 

3148 

3149 

3150add_newdoc('numpy._core.multiarray', 'ndarray', ('astype', 

3151 """ 

3152 a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True) 

3153 

3154 Copy of the array, cast to a specified type. 

3155 

3156 Parameters 

3157 ---------- 

3158 dtype : str or dtype 

3159 Typecode or data-type to which the array is cast. 

3160 order : {'C', 'F', 'A', 'K'}, optional 

3161 Controls the memory layout order of the result. 

3162 'C' means C order, 'F' means Fortran order, 'A' 

3163 means 'F' order if all the arrays are Fortran contiguous, 

3164 'C' order otherwise, and 'K' means as close to the 

3165 order the array elements appear in memory as possible. 

3166 Default is 'K'. 

3167 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional 

3168 Controls what kind of data casting may occur. Defaults to 'unsafe' 

3169 for backwards compatibility. 

3170 

3171 * 'no' means the data types should not be cast at all. 

3172 * 'equiv' means only byte-order changes are allowed. 

3173 * 'safe' means only casts which can preserve values are allowed. 

3174 * 'same_kind' means only safe casts or casts within a kind, 

3175 like float64 to float32, are allowed. 

3176 * 'unsafe' means any data conversions may be done. 

3177 subok : bool, optional 

3178 If True, then sub-classes will be passed-through (default), otherwise 

3179 the returned array will be forced to be a base-class array. 

3180 copy : bool, optional 

3181 By default, astype always returns a newly allocated array. If this 

3182 is set to false, and the `dtype`, `order`, and `subok` 

3183 requirements are satisfied, the input array is returned instead 

3184 of a copy. 

3185 

3186 Returns 

3187 ------- 

3188 arr_t : ndarray 

3189 Unless `copy` is False and the other conditions for returning the input 

3190 array are satisfied (see description for `copy` input parameter), `arr_t` 

3191 is a new array of the same shape as the input array, with dtype, order 

3192 given by `dtype`, `order`. 

3193 

3194 Notes 

3195 ----- 

3196 .. versionchanged:: 1.17.0 

3197 Casting between a simple data type and a structured one is possible only 

3198 for "unsafe" casting. Casting to multiple fields is allowed, but 

3199 casting from multiple fields is not. 

3200 

3201 .. versionchanged:: 1.9.0 

3202 Casting from numeric to string types in 'safe' casting mode requires 

3203 that the string dtype length is long enough to store the max 

3204 integer/float value converted. 

3205 

3206 Raises 

3207 ------ 

3208 ComplexWarning 

3209 When casting from complex to float or int. To avoid this, 

3210 one should use ``a.real.astype(t)``. 

3211 

3212 Examples 

3213 -------- 

3214 >>> x = np.array([1, 2, 2.5]) 

3215 >>> x 

3216 array([1. , 2. , 2.5]) 

3217 

3218 >>> x.astype(int) 

3219 array([1, 2, 2]) 

3220 

3221 """)) 

3222 

3223 

3224add_newdoc('numpy._core.multiarray', 'ndarray', ('byteswap', 

3225 """ 

3226 a.byteswap(inplace=False) 

3227 

3228 Swap the bytes of the array elements 

3229 

3230 Toggle between low-endian and big-endian data representation by 

3231 returning a byteswapped array, optionally swapped in-place. 

3232 Arrays of byte-strings are not swapped. The real and imaginary 

3233 parts of a complex number are swapped individually. 

3234 

3235 Parameters 

3236 ---------- 

3237 inplace : bool, optional 

3238 If ``True``, swap bytes in-place, default is ``False``. 

3239 

3240 Returns 

3241 ------- 

3242 out : ndarray 

3243 The byteswapped array. If `inplace` is ``True``, this is 

3244 a view to self. 

3245 

3246 Examples 

3247 -------- 

3248 >>> A = np.array([1, 256, 8755], dtype=np.int16) 

3249 >>> list(map(hex, A)) 

3250 ['0x1', '0x100', '0x2233'] 

3251 >>> A.byteswap(inplace=True) 

3252 array([ 256, 1, 13090], dtype=int16) 

3253 >>> list(map(hex, A)) 

3254 ['0x100', '0x1', '0x3322'] 

3255 

3256 Arrays of byte-strings are not swapped 

3257 

3258 >>> A = np.array([b'ceg', b'fac']) 

3259 >>> A.byteswap() 

3260 array([b'ceg', b'fac'], dtype='|S3') 

3261 

3262 ``A.view(A.dtype.newbyteorder()).byteswap()`` produces an array with 

3263 the same values but different representation in memory 

3264 

3265 >>> A = np.array([1, 2, 3]) 

3266 >>> A.view(np.uint8) 

3267 array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 

3268 0, 0], dtype=uint8) 

3269 >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True) 

3270 array([1, 2, 3]) 

3271 >>> A.view(np.uint8) 

3272 array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 

3273 0, 3], dtype=uint8) 

3274 

3275 """)) 

3276 

3277 

3278add_newdoc('numpy._core.multiarray', 'ndarray', ('choose', 

3279 """ 

3280 a.choose(choices, out=None, mode='raise') 

3281 

3282 Use an index array to construct a new array from a set of choices. 

3283 

3284 Refer to `numpy.choose` for full documentation. 

3285 

3286 See Also 

3287 -------- 

3288 numpy.choose : equivalent function 

3289 

3290 """)) 

3291 

3292 

3293add_newdoc('numpy._core.multiarray', 'ndarray', ('clip', 

3294 """ 

3295 a.clip(min=None, max=None, out=None, **kwargs) 

3296 

3297 Return an array whose values are limited to ``[min, max]``. 

3298 One of max or min must be given. 

3299 

3300 Refer to `numpy.clip` for full documentation. 

3301 

3302 See Also 

3303 -------- 

3304 numpy.clip : equivalent function 

3305 

3306 """)) 

3307 

3308 

3309add_newdoc('numpy._core.multiarray', 'ndarray', ('compress', 

3310 """ 

3311 a.compress(condition, axis=None, out=None) 

3312 

3313 Return selected slices of this array along given axis. 

3314 

3315 Refer to `numpy.compress` for full documentation. 

3316 

3317 See Also 

3318 -------- 

3319 numpy.compress : equivalent function 

3320 

3321 """)) 

3322 

3323 

3324add_newdoc('numpy._core.multiarray', 'ndarray', ('conj', 

3325 """ 

3326 a.conj() 

3327 

3328 Complex-conjugate all elements. 

3329 

3330 Refer to `numpy.conjugate` for full documentation. 

3331 

3332 See Also 

3333 -------- 

3334 numpy.conjugate : equivalent function 

3335 

3336 """)) 

3337 

3338 

3339add_newdoc('numpy._core.multiarray', 'ndarray', ('conjugate', 

3340 """ 

3341 a.conjugate() 

3342 

3343 Return the complex conjugate, element-wise. 

3344 

3345 Refer to `numpy.conjugate` for full documentation. 

3346 

3347 See Also 

3348 -------- 

3349 numpy.conjugate : equivalent function 

3350 

3351 """)) 

3352 

3353 

3354add_newdoc('numpy._core.multiarray', 'ndarray', ('copy', 

3355 """ 

3356 a.copy(order='C') 

3357 

3358 Return a copy of the array. 

3359 

3360 Parameters 

3361 ---------- 

3362 order : {'C', 'F', 'A', 'K'}, optional 

3363 Controls the memory layout of the copy. 'C' means C-order, 

3364 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 

3365 'C' otherwise. 'K' means match the layout of `a` as closely 

3366 as possible. (Note that this function and :func:`numpy.copy` are very 

3367 similar but have different default values for their order= 

3368 arguments, and this function always passes sub-classes through.) 

3369 

3370 See also 

3371 -------- 

3372 numpy.copy : Similar function with different default behavior 

3373 numpy.copyto 

3374 

3375 Notes 

3376 ----- 

3377 This function is the preferred method for creating an array copy. The 

3378 function :func:`numpy.copy` is similar, but it defaults to using order 'K', 

3379 and will not pass sub-classes through by default. 

3380 

3381 Examples 

3382 -------- 

3383 >>> x = np.array([[1,2,3],[4,5,6]], order='F') 

3384 

3385 >>> y = x.copy() 

3386 

3387 >>> x.fill(0) 

3388 

3389 >>> x 

3390 array([[0, 0, 0], 

3391 [0, 0, 0]]) 

3392 

3393 >>> y 

3394 array([[1, 2, 3], 

3395 [4, 5, 6]]) 

3396 

3397 >>> y.flags['C_CONTIGUOUS'] 

3398 True 

3399 

3400 For arrays containing Python objects (e.g. dtype=object), 

3401 the copy is a shallow one. The new array will contain the 

3402 same object which may lead to surprises if that object can 

3403 be modified (is mutable): 

3404 

3405 >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object) 

3406 >>> b = a.copy() 

3407 >>> b[2][0] = 10 

3408 >>> a 

3409 array([1, 'm', list([10, 3, 4])], dtype=object) 

3410 

3411 To ensure all elements within an ``object`` array are copied, 

3412 use `copy.deepcopy`: 

3413 

3414 >>> import copy 

3415 >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object) 

3416 >>> c = copy.deepcopy(a) 

3417 >>> c[2][0] = 10 

3418 >>> c 

3419 array([1, 'm', list([10, 3, 4])], dtype=object) 

3420 >>> a 

3421 array([1, 'm', list([2, 3, 4])], dtype=object) 

3422 

3423 """)) 

3424 

3425 

3426add_newdoc('numpy._core.multiarray', 'ndarray', ('cumprod', 

3427 """ 

3428 a.cumprod(axis=None, dtype=None, out=None) 

3429 

3430 Return the cumulative product of the elements along the given axis. 

3431 

3432 Refer to `numpy.cumprod` for full documentation. 

3433 

3434 See Also 

3435 -------- 

3436 numpy.cumprod : equivalent function 

3437 

3438 """)) 

3439 

3440 

3441add_newdoc('numpy._core.multiarray', 'ndarray', ('cumsum', 

3442 """ 

3443 a.cumsum(axis=None, dtype=None, out=None) 

3444 

3445 Return the cumulative sum of the elements along the given axis. 

3446 

3447 Refer to `numpy.cumsum` for full documentation. 

3448 

3449 See Also 

3450 -------- 

3451 numpy.cumsum : equivalent function 

3452 

3453 """)) 

3454 

3455 

3456add_newdoc('numpy._core.multiarray', 'ndarray', ('diagonal', 

3457 """ 

3458 a.diagonal(offset=0, axis1=0, axis2=1) 

3459 

3460 Return specified diagonals. In NumPy 1.9 the returned array is a 

3461 read-only view instead of a copy as in previous NumPy versions. In 

3462 a future version the read-only restriction will be removed. 

3463 

3464 Refer to :func:`numpy.diagonal` for full documentation. 

3465 

3466 See Also 

3467 -------- 

3468 numpy.diagonal : equivalent function 

3469 

3470 """)) 

3471 

3472 

3473add_newdoc('numpy._core.multiarray', 'ndarray', ('dot')) 

3474 

3475 

3476add_newdoc('numpy._core.multiarray', 'ndarray', ('dump', 

3477 """ 

3478 a.dump(file) 

3479 

3480 Dump a pickle of the array to the specified file. 

3481 The array can be read back with pickle.load or numpy.load. 

3482 

3483 Parameters 

3484 ---------- 

3485 file : str or Path 

3486 A string naming the dump file. 

3487 

3488 .. versionchanged:: 1.17.0 

3489 `pathlib.Path` objects are now accepted. 

3490 

3491 """)) 

3492 

3493 

3494add_newdoc('numpy._core.multiarray', 'ndarray', ('dumps', 

3495 """ 

3496 a.dumps() 

3497 

3498 Returns the pickle of the array as a string. 

3499 pickle.loads will convert the string back to an array. 

3500 

3501 Parameters 

3502 ---------- 

3503 None 

3504 

3505 """)) 

3506 

3507 

3508add_newdoc('numpy._core.multiarray', 'ndarray', ('fill', 

3509 """ 

3510 a.fill(value) 

3511 

3512 Fill the array with a scalar value. 

3513 

3514 Parameters 

3515 ---------- 

3516 value : scalar 

3517 All elements of `a` will be assigned this value. 

3518 

3519 Examples 

3520 -------- 

3521 >>> a = np.array([1, 2]) 

3522 >>> a.fill(0) 

3523 >>> a 

3524 array([0, 0]) 

3525 >>> a = np.empty(2) 

3526 >>> a.fill(1) 

3527 >>> a 

3528 array([1., 1.]) 

3529 

3530 Fill expects a scalar value and always behaves the same as assigning 

3531 to a single array element. The following is a rare example where this 

3532 distinction is important: 

3533 

3534 >>> a = np.array([None, None], dtype=object) 

3535 >>> a[0] = np.array(3) 

3536 >>> a 

3537 array([array(3), None], dtype=object) 

3538 >>> a.fill(np.array(3)) 

3539 >>> a 

3540 array([array(3), array(3)], dtype=object) 

3541 

3542 Where other forms of assignments will unpack the array being assigned: 

3543 

3544 >>> a[...] = np.array(3) 

3545 >>> a 

3546 array([3, 3], dtype=object) 

3547 

3548 """)) 

3549 

3550 

3551add_newdoc('numpy._core.multiarray', 'ndarray', ('flatten', 

3552 """ 

3553 a.flatten(order='C') 

3554 

3555 Return a copy of the array collapsed into one dimension. 

3556 

3557 Parameters 

3558 ---------- 

3559 order : {'C', 'F', 'A', 'K'}, optional 

3560 'C' means to flatten in row-major (C-style) order. 

3561 'F' means to flatten in column-major (Fortran- 

3562 style) order. 'A' means to flatten in column-major 

3563 order if `a` is Fortran *contiguous* in memory, 

3564 row-major order otherwise. 'K' means to flatten 

3565 `a` in the order the elements occur in memory. 

3566 The default is 'C'. 

3567 

3568 Returns 

3569 ------- 

3570 y : ndarray 

3571 A copy of the input array, flattened to one dimension. 

3572 

3573 See Also 

3574 -------- 

3575 ravel : Return a flattened array. 

3576 flat : A 1-D flat iterator over the array. 

3577 

3578 Examples 

3579 -------- 

3580 >>> a = np.array([[1,2], [3,4]]) 

3581 >>> a.flatten() 

3582 array([1, 2, 3, 4]) 

3583 >>> a.flatten('F') 

3584 array([1, 3, 2, 4]) 

3585 

3586 """)) 

3587 

3588 

3589add_newdoc('numpy._core.multiarray', 'ndarray', ('getfield', 

3590 """ 

3591 a.getfield(dtype, offset=0) 

3592 

3593 Returns a field of the given array as a certain type. 

3594 

3595 A field is a view of the array data with a given data-type. The values in 

3596 the view are determined by the given type and the offset into the current 

3597 array in bytes. The offset needs to be such that the view dtype fits in the 

3598 array dtype; for example an array of dtype complex128 has 16-byte elements. 

3599 If taking a view with a 32-bit integer (4 bytes), the offset needs to be 

3600 between 0 and 12 bytes. 

3601 

3602 Parameters 

3603 ---------- 

3604 dtype : str or dtype 

3605 The data type of the view. The dtype size of the view can not be larger 

3606 than that of the array itself. 

3607 offset : int 

3608 Number of bytes to skip before beginning the element view. 

3609 

3610 Examples 

3611 -------- 

3612 >>> x = np.diag([1.+1.j]*2) 

3613 >>> x[1, 1] = 2 + 4.j 

3614 >>> x 

3615 array([[1.+1.j, 0.+0.j], 

3616 [0.+0.j, 2.+4.j]]) 

3617 >>> x.getfield(np.float64) 

3618 array([[1., 0.], 

3619 [0., 2.]]) 

3620 

3621 By choosing an offset of 8 bytes we can select the complex part of the 

3622 array for our view: 

3623 

3624 >>> x.getfield(np.float64, offset=8) 

3625 array([[1., 0.], 

3626 [0., 4.]]) 

3627 

3628 """)) 

3629 

3630 

3631add_newdoc('numpy._core.multiarray', 'ndarray', ('item', 

3632 """ 

3633 a.item(*args) 

3634 

3635 Copy an element of an array to a standard Python scalar and return it. 

3636 

3637 Parameters 

3638 ---------- 

3639 \\*args : Arguments (variable number and type) 

3640 

3641 * none: in this case, the method only works for arrays 

3642 with one element (`a.size == 1`), which element is 

3643 copied into a standard Python scalar object and returned. 

3644 

3645 * int_type: this argument is interpreted as a flat index into 

3646 the array, specifying which element to copy and return. 

3647 

3648 * tuple of int_types: functions as does a single int_type argument, 

3649 except that the argument is interpreted as an nd-index into the 

3650 array. 

3651 

3652 Returns 

3653 ------- 

3654 z : Standard Python scalar object 

3655 A copy of the specified element of the array as a suitable 

3656 Python scalar 

3657 

3658 Notes 

3659 ----- 

3660 When the data type of `a` is longdouble or clongdouble, item() returns 

3661 a scalar array object because there is no available Python scalar that 

3662 would not lose information. Void arrays return a buffer object for item(), 

3663 unless fields are defined, in which case a tuple is returned. 

3664 

3665 `item` is very similar to a[args], except, instead of an array scalar, 

3666 a standard Python scalar is returned. This can be useful for speeding up 

3667 access to elements of the array and doing arithmetic on elements of the 

3668 array using Python's optimized math. 

3669 

3670 Examples 

3671 -------- 

3672 >>> np.random.seed(123) 

3673 >>> x = np.random.randint(9, size=(3, 3)) 

3674 >>> x 

3675 array([[2, 2, 6], 

3676 [1, 3, 6], 

3677 [1, 0, 1]]) 

3678 >>> x.item(3) 

3679 1 

3680 >>> x.item(7) 

3681 0 

3682 >>> x.item((0, 1)) 

3683 2 

3684 >>> x.item((2, 2)) 

3685 1 

3686 

3687 For an array with object dtype, elements are returned as-is. 

3688 

3689 >>> a = np.array([np.int64(1)], dtype=object) 

3690 >>> a.item() #return np.int64 

3691 np.int64(1) 

3692 

3693 """)) 

3694 

3695 

3696add_newdoc('numpy._core.multiarray', 'ndarray', ('max', 

3697 """ 

3698 a.max(axis=None, out=None, keepdims=False, initial=<no value>, where=True) 

3699 

3700 Return the maximum along a given axis. 

3701 

3702 Refer to `numpy.amax` for full documentation. 

3703 

3704 See Also 

3705 -------- 

3706 numpy.amax : equivalent function 

3707 

3708 """)) 

3709 

3710 

3711add_newdoc('numpy._core.multiarray', 'ndarray', ('mean', 

3712 """ 

3713 a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True) 

3714 

3715 Returns the average of the array elements along given axis. 

3716 

3717 Refer to `numpy.mean` for full documentation. 

3718 

3719 See Also 

3720 -------- 

3721 numpy.mean : equivalent function 

3722 

3723 """)) 

3724 

3725 

3726add_newdoc('numpy._core.multiarray', 'ndarray', ('min', 

3727 """ 

3728 a.min(axis=None, out=None, keepdims=False, initial=<no value>, where=True) 

3729 

3730 Return the minimum along a given axis. 

3731 

3732 Refer to `numpy.amin` for full documentation. 

3733 

3734 See Also 

3735 -------- 

3736 numpy.amin : equivalent function 

3737 

3738 """)) 

3739 

3740 

3741add_newdoc('numpy._core.multiarray', 'ndarray', ('nonzero', 

3742 """ 

3743 a.nonzero() 

3744 

3745 Return the indices of the elements that are non-zero. 

3746 

3747 Refer to `numpy.nonzero` for full documentation. 

3748 

3749 See Also 

3750 -------- 

3751 numpy.nonzero : equivalent function 

3752 

3753 """)) 

3754 

3755 

3756add_newdoc('numpy._core.multiarray', 'ndarray', ('prod', 

3757 """ 

3758 a.prod(axis=None, dtype=None, out=None, keepdims=False, 

3759 initial=1, where=True) 

3760 

3761 Return the product of the array elements over the given axis 

3762 

3763 Refer to `numpy.prod` for full documentation. 

3764 

3765 See Also 

3766 -------- 

3767 numpy.prod : equivalent function 

3768 

3769 """)) 

3770 

3771 

3772add_newdoc('numpy._core.multiarray', 'ndarray', ('put', 

3773 """ 

3774 a.put(indices, values, mode='raise') 

3775 

3776 Set ``a.flat[n] = values[n]`` for all `n` in indices. 

3777 

3778 Refer to `numpy.put` for full documentation. 

3779 

3780 See Also 

3781 -------- 

3782 numpy.put : equivalent function 

3783 

3784 """)) 

3785 

3786 

3787add_newdoc('numpy._core.multiarray', 'ndarray', ('ravel', 

3788 """ 

3789 a.ravel([order]) 

3790 

3791 Return a flattened array. 

3792 

3793 Refer to `numpy.ravel` for full documentation. 

3794 

3795 See Also 

3796 -------- 

3797 numpy.ravel : equivalent function 

3798 

3799 ndarray.flat : a flat iterator on the array. 

3800 

3801 """)) 

3802 

3803 

3804add_newdoc('numpy._core.multiarray', 'ndarray', ('repeat', 

3805 """ 

3806 a.repeat(repeats, axis=None) 

3807 

3808 Repeat elements of an array. 

3809 

3810 Refer to `numpy.repeat` for full documentation. 

3811 

3812 See Also 

3813 -------- 

3814 numpy.repeat : equivalent function 

3815 

3816 """)) 

3817 

3818 

3819add_newdoc('numpy._core.multiarray', 'ndarray', ('reshape', 

3820 """ 

3821 a.reshape(shape, /, *, order='C') 

3822 

3823 Returns an array containing the same data with a new shape. 

3824 

3825 Refer to `numpy.reshape` for full documentation. 

3826 

3827 See Also 

3828 -------- 

3829 numpy.reshape : equivalent function 

3830 

3831 Notes 

3832 ----- 

3833 Unlike the free function `numpy.reshape`, this method on `ndarray` allows 

3834 the elements of the shape parameter to be passed in as separate arguments. 

3835 For example, ``a.reshape(10, 11)`` is equivalent to 

3836 ``a.reshape((10, 11))``. 

3837 

3838 """)) 

3839 

3840 

3841add_newdoc('numpy._core.multiarray', 'ndarray', ('resize', 

3842 """ 

3843 a.resize(new_shape, refcheck=True) 

3844 

3845 Change shape and size of array in-place. 

3846 

3847 Parameters 

3848 ---------- 

3849 new_shape : tuple of ints, or `n` ints 

3850 Shape of resized array. 

3851 refcheck : bool, optional 

3852 If False, reference count will not be checked. Default is True. 

3853 

3854 Returns 

3855 ------- 

3856 None 

3857 

3858 Raises 

3859 ------ 

3860 ValueError 

3861 If `a` does not own its own data or references or views to it exist, 

3862 and the data memory must be changed. 

3863 PyPy only: will always raise if the data memory must be changed, since 

3864 there is no reliable way to determine if references or views to it 

3865 exist. 

3866 

3867 SystemError 

3868 If the `order` keyword argument is specified. This behaviour is a 

3869 bug in NumPy. 

3870 

3871 See Also 

3872 -------- 

3873 resize : Return a new array with the specified shape. 

3874 

3875 Notes 

3876 ----- 

3877 This reallocates space for the data area if necessary. 

3878 

3879 Only contiguous arrays (data elements consecutive in memory) can be 

3880 resized. 

3881 

3882 The purpose of the reference count check is to make sure you 

3883 do not use this array as a buffer for another Python object and then 

3884 reallocate the memory. However, reference counts can increase in 

3885 other ways so if you are sure that you have not shared the memory 

3886 for this array with another Python object, then you may safely set 

3887 `refcheck` to False. 

3888 

3889 Examples 

3890 -------- 

3891 Shrinking an array: array is flattened (in the order that the data are 

3892 stored in memory), resized, and reshaped: 

3893 

3894 >>> a = np.array([[0, 1], [2, 3]], order='C') 

3895 >>> a.resize((2, 1)) 

3896 >>> a 

3897 array([[0], 

3898 [1]]) 

3899 

3900 >>> a = np.array([[0, 1], [2, 3]], order='F') 

3901 >>> a.resize((2, 1)) 

3902 >>> a 

3903 array([[0], 

3904 [2]]) 

3905 

3906 Enlarging an array: as above, but missing entries are filled with zeros: 

3907 

3908 >>> b = np.array([[0, 1], [2, 3]]) 

3909 >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple 

3910 >>> b 

3911 array([[0, 1, 2], 

3912 [3, 0, 0]]) 

3913 

3914 Referencing an array prevents resizing... 

3915 

3916 >>> c = a 

3917 >>> a.resize((1, 1)) 

3918 Traceback (most recent call last): 

3919 ... 

3920 ValueError: cannot resize an array that references or is referenced ... 

3921 

3922 Unless `refcheck` is False: 

3923 

3924 >>> a.resize((1, 1), refcheck=False) 

3925 >>> a 

3926 array([[0]]) 

3927 >>> c 

3928 array([[0]]) 

3929 

3930 """)) 

3931 

3932 

3933add_newdoc('numpy._core.multiarray', 'ndarray', ('round', 

3934 """ 

3935 a.round(decimals=0, out=None) 

3936 

3937 Return `a` with each element rounded to the given number of decimals. 

3938 

3939 Refer to `numpy.around` for full documentation. 

3940 

3941 See Also 

3942 -------- 

3943 numpy.around : equivalent function 

3944 

3945 """)) 

3946 

3947 

3948add_newdoc('numpy._core.multiarray', 'ndarray', ('searchsorted', 

3949 """ 

3950 a.searchsorted(v, side='left', sorter=None) 

3951 

3952 Find indices where elements of v should be inserted in a to maintain order. 

3953 

3954 For full documentation, see `numpy.searchsorted` 

3955 

3956 See Also 

3957 -------- 

3958 numpy.searchsorted : equivalent function 

3959 

3960 """)) 

3961 

3962 

3963add_newdoc('numpy._core.multiarray', 'ndarray', ('setfield', 

3964 """ 

3965 a.setfield(val, dtype, offset=0) 

3966 

3967 Put a value into a specified place in a field defined by a data-type. 

3968 

3969 Place `val` into `a`'s field defined by `dtype` and beginning `offset` 

3970 bytes into the field. 

3971 

3972 Parameters 

3973 ---------- 

3974 val : object 

3975 Value to be placed in field. 

3976 dtype : dtype object 

3977 Data-type of the field in which to place `val`. 

3978 offset : int, optional 

3979 The number of bytes into the field at which to place `val`. 

3980 

3981 Returns 

3982 ------- 

3983 None 

3984 

3985 See Also 

3986 -------- 

3987 getfield 

3988 

3989 Examples 

3990 -------- 

3991 >>> x = np.eye(3) 

3992 >>> x.getfield(np.float64) 

3993 array([[1., 0., 0.], 

3994 [0., 1., 0.], 

3995 [0., 0., 1.]]) 

3996 >>> x.setfield(3, np.int32) 

3997 >>> x.getfield(np.int32) 

3998 array([[3, 3, 3], 

3999 [3, 3, 3], 

4000 [3, 3, 3]], dtype=int32) 

4001 >>> x 

4002 array([[1.0e+000, 1.5e-323, 1.5e-323], 

4003 [1.5e-323, 1.0e+000, 1.5e-323], 

4004 [1.5e-323, 1.5e-323, 1.0e+000]]) 

4005 >>> x.setfield(np.eye(3), np.int32) 

4006 >>> x 

4007 array([[1., 0., 0.], 

4008 [0., 1., 0.], 

4009 [0., 0., 1.]]) 

4010 

4011 """)) 

4012 

4013 

4014add_newdoc('numpy._core.multiarray', 'ndarray', ('setflags', 

4015 """ 

4016 a.setflags(write=None, align=None, uic=None) 

4017 

4018 Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY, 

4019 respectively. 

4020 

4021 These Boolean-valued flags affect how numpy interprets the memory 

4022 area used by `a` (see Notes below). The ALIGNED flag can only 

4023 be set to True if the data is actually aligned according to the type. 

4024 The WRITEBACKIFCOPY flag can never be set 

4025 to True. The flag WRITEABLE can only be set to True if the array owns its 

4026 own memory, or the ultimate owner of the memory exposes a writeable buffer 

4027 interface, or is a string. (The exception for string is made so that 

4028 unpickling can be done without copying memory.) 

4029 

4030 Parameters 

4031 ---------- 

4032 write : bool, optional 

4033 Describes whether or not `a` can be written to. 

4034 align : bool, optional 

4035 Describes whether or not `a` is aligned properly for its type. 

4036 uic : bool, optional 

4037 Describes whether or not `a` is a copy of another "base" array. 

4038 

4039 Notes 

4040 ----- 

4041 Array flags provide information about how the memory area used 

4042 for the array is to be interpreted. There are 7 Boolean flags 

4043 in use, only three of which can be changed by the user: 

4044 WRITEBACKIFCOPY, WRITEABLE, and ALIGNED. 

4045 

4046 WRITEABLE (W) the data area can be written to; 

4047 

4048 ALIGNED (A) the data and strides are aligned appropriately for the hardware 

4049 (as determined by the compiler); 

4050 

4051 WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced 

4052 by .base). When the C-API function PyArray_ResolveWritebackIfCopy is 

4053 called, the base array will be updated with the contents of this array. 

4054 

4055 All flags can be accessed using the single (upper case) letter as well 

4056 as the full name. 

4057 

4058 Examples 

4059 -------- 

4060 >>> y = np.array([[3, 1, 7], 

4061 ... [2, 0, 0], 

4062 ... [8, 5, 9]]) 

4063 >>> y 

4064 array([[3, 1, 7], 

4065 [2, 0, 0], 

4066 [8, 5, 9]]) 

4067 >>> y.flags 

4068 C_CONTIGUOUS : True 

4069 F_CONTIGUOUS : False 

4070 OWNDATA : True 

4071 WRITEABLE : True 

4072 ALIGNED : True 

4073 WRITEBACKIFCOPY : False 

4074 >>> y.setflags(write=0, align=0) 

4075 >>> y.flags 

4076 C_CONTIGUOUS : True 

4077 F_CONTIGUOUS : False 

4078 OWNDATA : True 

4079 WRITEABLE : False 

4080 ALIGNED : False 

4081 WRITEBACKIFCOPY : False 

4082 >>> y.setflags(uic=1) 

4083 Traceback (most recent call last): 

4084 File "<stdin>", line 1, in <module> 

4085 ValueError: cannot set WRITEBACKIFCOPY flag to True 

4086 

4087 """)) 

4088 

4089 

4090add_newdoc('numpy._core.multiarray', 'ndarray', ('sort', 

4091 """ 

4092 a.sort(axis=-1, kind=None, order=None) 

4093 

4094 Sort an array in-place. Refer to `numpy.sort` for full documentation. 

4095 

4096 Parameters 

4097 ---------- 

4098 axis : int, optional 

4099 Axis along which to sort. Default is -1, which means sort along the 

4100 last axis. 

4101 kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional 

4102 Sorting algorithm. The default is 'quicksort'. Note that both 'stable' 

4103 and 'mergesort' use timsort under the covers and, in general, the 

4104 actual implementation will vary with datatype. The 'mergesort' option 

4105 is retained for backwards compatibility. 

4106 

4107 .. versionchanged:: 1.15.0 

4108 The 'stable' option was added. 

4109 

4110 order : str or list of str, optional 

4111 When `a` is an array with fields defined, this argument specifies 

4112 which fields to compare first, second, etc. A single field can 

4113 be specified as a string, and not all fields need be specified, 

4114 but unspecified fields will still be used, in the order in which 

4115 they come up in the dtype, to break ties. 

4116 

4117 See Also 

4118 -------- 

4119 numpy.sort : Return a sorted copy of an array. 

4120 numpy.argsort : Indirect sort. 

4121 numpy.lexsort : Indirect stable sort on multiple keys. 

4122 numpy.searchsorted : Find elements in sorted array. 

4123 numpy.partition: Partial sort. 

4124 

4125 Notes 

4126 ----- 

4127 See `numpy.sort` for notes on the different sorting algorithms. 

4128 

4129 Examples 

4130 -------- 

4131 >>> a = np.array([[1,4], [3,1]]) 

4132 >>> a.sort(axis=1) 

4133 >>> a 

4134 array([[1, 4], 

4135 [1, 3]]) 

4136 >>> a.sort(axis=0) 

4137 >>> a 

4138 array([[1, 3], 

4139 [1, 4]]) 

4140 

4141 Use the `order` keyword to specify a field to use when sorting a 

4142 structured array: 

4143 

4144 >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)]) 

4145 >>> a.sort(order='y') 

4146 >>> a 

4147 array([(b'c', 1), (b'a', 2)], 

4148 dtype=[('x', 'S1'), ('y', '<i8')]) 

4149 

4150 """)) 

4151 

4152 

4153add_newdoc('numpy._core.multiarray', 'ndarray', ('partition', 

4154 """ 

4155 a.partition(kth, axis=-1, kind='introselect', order=None) 

4156 

4157 Partially sorts the elements in the array in such a way that the value of 

4158 the element in k-th position is in the position it would be in a sorted 

4159 array. In the output array, all elements smaller than the k-th element 

4160 are located to the left of this element and all equal or greater are 

4161 located to its right. The ordering of the elements in the two partitions 

4162 on the either side of the k-th element in the output array is undefined. 

4163 

4164 .. versionadded:: 1.8.0 

4165 

4166 Parameters 

4167 ---------- 

4168 kth : int or sequence of ints 

4169 Element index to partition by. The kth element value will be in its 

4170 final sorted position and all smaller elements will be moved before it 

4171 and all equal or greater elements behind it. 

4172 The order of all elements in the partitions is undefined. 

4173 If provided with a sequence of kth it will partition all elements 

4174 indexed by kth of them into their sorted position at once. 

4175 

4176 .. deprecated:: 1.22.0 

4177 Passing booleans as index is deprecated. 

4178 axis : int, optional 

4179 Axis along which to sort. Default is -1, which means sort along the 

4180 last axis. 

4181 kind : {'introselect'}, optional 

4182 Selection algorithm. Default is 'introselect'. 

4183 order : str or list of str, optional 

4184 When `a` is an array with fields defined, this argument specifies 

4185 which fields to compare first, second, etc. A single field can 

4186 be specified as a string, and not all fields need to be specified, 

4187 but unspecified fields will still be used, in the order in which 

4188 they come up in the dtype, to break ties. 

4189 

4190 See Also 

4191 -------- 

4192 numpy.partition : Return a partitioned copy of an array. 

4193 argpartition : Indirect partition. 

4194 sort : Full sort. 

4195 

4196 Notes 

4197 ----- 

4198 See ``np.partition`` for notes on the different algorithms. 

4199 

4200 Examples 

4201 -------- 

4202 >>> a = np.array([3, 4, 2, 1]) 

4203 >>> a.partition(3) 

4204 >>> a 

4205 array([2, 1, 3, 4]) # may vary 

4206 

4207 >>> a.partition((1, 3)) 

4208 >>> a 

4209 array([1, 2, 3, 4]) 

4210 """)) 

4211 

4212 

4213add_newdoc('numpy._core.multiarray', 'ndarray', ('squeeze', 

4214 """ 

4215 a.squeeze(axis=None) 

4216 

4217 Remove axes of length one from `a`. 

4218 

4219 Refer to `numpy.squeeze` for full documentation. 

4220 

4221 See Also 

4222 -------- 

4223 numpy.squeeze : equivalent function 

4224 

4225 """)) 

4226 

4227 

4228add_newdoc('numpy._core.multiarray', 'ndarray', ('std', 

4229 """ 

4230 a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True) 

4231 

4232 Returns the standard deviation of the array elements along given axis. 

4233 

4234 Refer to `numpy.std` for full documentation. 

4235 

4236 See Also 

4237 -------- 

4238 numpy.std : equivalent function 

4239 

4240 """)) 

4241 

4242 

4243add_newdoc('numpy._core.multiarray', 'ndarray', ('sum', 

4244 """ 

4245 a.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True) 

4246 

4247 Return the sum of the array elements over the given axis. 

4248 

4249 Refer to `numpy.sum` for full documentation. 

4250 

4251 See Also 

4252 -------- 

4253 numpy.sum : equivalent function 

4254 

4255 """)) 

4256 

4257 

4258add_newdoc('numpy._core.multiarray', 'ndarray', ('swapaxes', 

4259 """ 

4260 a.swapaxes(axis1, axis2) 

4261 

4262 Return a view of the array with `axis1` and `axis2` interchanged. 

4263 

4264 Refer to `numpy.swapaxes` for full documentation. 

4265 

4266 See Also 

4267 -------- 

4268 numpy.swapaxes : equivalent function 

4269 

4270 """)) 

4271 

4272 

4273add_newdoc('numpy._core.multiarray', 'ndarray', ('take', 

4274 """ 

4275 a.take(indices, axis=None, out=None, mode='raise') 

4276 

4277 Return an array formed from the elements of `a` at the given indices. 

4278 

4279 Refer to `numpy.take` for full documentation. 

4280 

4281 See Also 

4282 -------- 

4283 numpy.take : equivalent function 

4284 

4285 """)) 

4286 

4287 

4288add_newdoc('numpy._core.multiarray', 'ndarray', ('tofile', 

4289 """ 

4290 a.tofile(fid, sep="", format="%s") 

4291 

4292 Write array to a file as text or binary (default). 

4293 

4294 Data is always written in 'C' order, independent of the order of `a`. 

4295 The data produced by this method can be recovered using the function 

4296 fromfile(). 

4297 

4298 Parameters 

4299 ---------- 

4300 fid : file or str or Path 

4301 An open file object, or a string containing a filename. 

4302 

4303 .. versionchanged:: 1.17.0 

4304 `pathlib.Path` objects are now accepted. 

4305 

4306 sep : str 

4307 Separator between array items for text output. 

4308 If "" (empty), a binary file is written, equivalent to 

4309 ``file.write(a.tobytes())``. 

4310 format : str 

4311 Format string for text file output. 

4312 Each entry in the array is formatted to text by first converting 

4313 it to the closest Python type, and then using "format" % item. 

4314 

4315 Notes 

4316 ----- 

4317 This is a convenience function for quick storage of array data. 

4318 Information on endianness and precision is lost, so this method is not a 

4319 good choice for files intended to archive data or transport data between 

4320 machines with different endianness. Some of these problems can be overcome 

4321 by outputting the data as text files, at the expense of speed and file 

4322 size. 

4323 

4324 When fid is a file object, array contents are directly written to the 

4325 file, bypassing the file object's ``write`` method. As a result, tofile 

4326 cannot be used with files objects supporting compression (e.g., GzipFile) 

4327 or file-like objects that do not support ``fileno()`` (e.g., BytesIO). 

4328 

4329 """)) 

4330 

4331 

4332add_newdoc('numpy._core.multiarray', 'ndarray', ('tolist', 

4333 """ 

4334 a.tolist() 

4335 

4336 Return the array as an ``a.ndim``-levels deep nested list of Python scalars. 

4337 

4338 Return a copy of the array data as a (nested) Python list. 

4339 Data items are converted to the nearest compatible builtin Python type, via 

4340 the `~numpy.ndarray.item` function. 

4341 

4342 If ``a.ndim`` is 0, then since the depth of the nested list is 0, it will 

4343 not be a list at all, but a simple Python scalar. 

4344 

4345 Parameters 

4346 ---------- 

4347 none 

4348 

4349 Returns 

4350 ------- 

4351 y : object, or list of object, or list of list of object, or ... 

4352 The possibly nested list of array elements. 

4353 

4354 Notes 

4355 ----- 

4356 The array may be recreated via ``a = np.array(a.tolist())``, although this 

4357 may sometimes lose precision. 

4358 

4359 Examples 

4360 -------- 

4361 For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``, 

4362 except that ``tolist`` changes numpy scalars to Python scalars: 

4363 

4364 >>> a = np.uint32([1, 2]) 

4365 >>> a_list = list(a) 

4366 >>> a_list 

4367 [1, 2] 

4368 >>> type(a_list[0]) 

4369 <class 'numpy.uint32'> 

4370 >>> a_tolist = a.tolist() 

4371 >>> a_tolist 

4372 [1, 2] 

4373 >>> type(a_tolist[0]) 

4374 <class 'int'> 

4375 

4376 Additionally, for a 2D array, ``tolist`` applies recursively: 

4377 

4378 >>> a = np.array([[1, 2], [3, 4]]) 

4379 >>> list(a) 

4380 [array([1, 2]), array([3, 4])] 

4381 >>> a.tolist() 

4382 [[1, 2], [3, 4]] 

4383 

4384 The base case for this recursion is a 0D array: 

4385 

4386 >>> a = np.array(1) 

4387 >>> list(a) 

4388 Traceback (most recent call last): 

4389 ... 

4390 TypeError: iteration over a 0-d array 

4391 >>> a.tolist() 

4392 1 

4393 """)) 

4394 

4395 

4396add_newdoc('numpy._core.multiarray', 'ndarray', ('tobytes', """ 

4397 a.tobytes(order='C') 

4398 

4399 Construct Python bytes containing the raw data bytes in the array. 

4400 

4401 Constructs Python bytes showing a copy of the raw contents of 

4402 data memory. The bytes object is produced in C-order by default. 

4403 This behavior is controlled by the ``order`` parameter. 

4404 

4405 .. versionadded:: 1.9.0 

4406 

4407 Parameters 

4408 ---------- 

4409 order : {'C', 'F', 'A'}, optional 

4410 Controls the memory layout of the bytes object. 'C' means C-order, 

4411 'F' means F-order, 'A' (short for *Any*) means 'F' if `a` is 

4412 Fortran contiguous, 'C' otherwise. Default is 'C'. 

4413 

4414 Returns 

4415 ------- 

4416 s : bytes 

4417 Python bytes exhibiting a copy of `a`'s raw data. 

4418 

4419 See also 

4420 -------- 

4421 frombuffer 

4422 Inverse of this operation, construct a 1-dimensional array from Python 

4423 bytes. 

4424 

4425 Examples 

4426 -------- 

4427 >>> x = np.array([[0, 1], [2, 3]], dtype='<u2') 

4428 >>> x.tobytes() 

4429 b'\\x00\\x00\\x01\\x00\\x02\\x00\\x03\\x00' 

4430 >>> x.tobytes('C') == x.tobytes() 

4431 True 

4432 >>> x.tobytes('F') 

4433 b'\\x00\\x00\\x02\\x00\\x01\\x00\\x03\\x00' 

4434 

4435 """)) 

4436 

4437 

4438add_newdoc('numpy._core.multiarray', 'ndarray', ('tostring', r""" 

4439 a.tostring(order='C') 

4440 

4441 A compatibility alias for `~ndarray.tobytes`, with exactly the same 

4442 behavior. 

4443 

4444 Despite its name, it returns :class:`bytes` not :class:`str`\ s. 

4445 

4446 .. deprecated:: 1.19.0 

4447 """)) 

4448 

4449 

4450add_newdoc('numpy._core.multiarray', 'ndarray', ('trace', 

4451 """ 

4452 a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None) 

4453 

4454 Return the sum along diagonals of the array. 

4455 

4456 Refer to `numpy.trace` for full documentation. 

4457 

4458 See Also 

4459 -------- 

4460 numpy.trace : equivalent function 

4461 

4462 """)) 

4463 

4464 

4465add_newdoc('numpy._core.multiarray', 'ndarray', ('transpose', 

4466 """ 

4467 a.transpose(*axes) 

4468 

4469 Returns a view of the array with axes transposed. 

4470 

4471 Refer to `numpy.transpose` for full documentation. 

4472 

4473 Parameters 

4474 ---------- 

4475 axes : None, tuple of ints, or `n` ints 

4476 

4477 * None or no argument: reverses the order of the axes. 

4478 

4479 * tuple of ints: `i` in the `j`-th place in the tuple means that the 

4480 array's `i`-th axis becomes the transposed array's `j`-th axis. 

4481 

4482 * `n` ints: same as an n-tuple of the same ints (this form is 

4483 intended simply as a "convenience" alternative to the tuple form). 

4484 

4485 Returns 

4486 ------- 

4487 p : ndarray 

4488 View of the array with its axes suitably permuted. 

4489 

4490 See Also 

4491 -------- 

4492 transpose : Equivalent function. 

4493 ndarray.T : Array property returning the array transposed. 

4494 ndarray.reshape : Give a new shape to an array without changing its data. 

4495 

4496 Examples 

4497 -------- 

4498 >>> a = np.array([[1, 2], [3, 4]]) 

4499 >>> a 

4500 array([[1, 2], 

4501 [3, 4]]) 

4502 >>> a.transpose() 

4503 array([[1, 3], 

4504 [2, 4]]) 

4505 >>> a.transpose((1, 0)) 

4506 array([[1, 3], 

4507 [2, 4]]) 

4508 >>> a.transpose(1, 0) 

4509 array([[1, 3], 

4510 [2, 4]]) 

4511 

4512 >>> a = np.array([1, 2, 3, 4]) 

4513 >>> a 

4514 array([1, 2, 3, 4]) 

4515 >>> a.transpose() 

4516 array([1, 2, 3, 4]) 

4517 

4518 """)) 

4519 

4520 

4521add_newdoc('numpy._core.multiarray', 'ndarray', ('var', 

4522 """ 

4523 a.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True) 

4524 

4525 Returns the variance of the array elements, along given axis. 

4526 

4527 Refer to `numpy.var` for full documentation. 

4528 

4529 See Also 

4530 -------- 

4531 numpy.var : equivalent function 

4532 

4533 """)) 

4534 

4535 

4536add_newdoc('numpy._core.multiarray', 'ndarray', ('view', 

4537 """ 

4538 a.view([dtype][, type]) 

4539 

4540 New view of array with the same data. 

4541 

4542 .. note:: 

4543 Passing None for ``dtype`` is different from omitting the parameter, 

4544 since the former invokes ``dtype(None)`` which is an alias for 

4545 ``dtype('float64')``. 

4546 

4547 Parameters 

4548 ---------- 

4549 dtype : data-type or ndarray sub-class, optional 

4550 Data-type descriptor of the returned view, e.g., float32 or int16. 

4551 Omitting it results in the view having the same data-type as `a`. 

4552 This argument can also be specified as an ndarray sub-class, which 

4553 then specifies the type of the returned object (this is equivalent to 

4554 setting the ``type`` parameter). 

4555 type : Python type, optional 

4556 Type of the returned view, e.g., ndarray or matrix. Again, omission 

4557 of the parameter results in type preservation. 

4558 

4559 Notes 

4560 ----- 

4561 ``a.view()`` is used two different ways: 

4562 

4563 ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view 

4564 of the array's memory with a different data-type. This can cause a 

4565 reinterpretation of the bytes of memory. 

4566 

4567 ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just 

4568 returns an instance of `ndarray_subclass` that looks at the same array 

4569 (same shape, dtype, etc.) This does not cause a reinterpretation of the 

4570 memory. 

4571 

4572 For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of 

4573 bytes per entry than the previous dtype (for example, converting a regular 

4574 array to a structured array), then the last axis of ``a`` must be 

4575 contiguous. This axis will be resized in the result. 

4576 

4577 .. versionchanged:: 1.23.0 

4578 Only the last axis needs to be contiguous. Previously, the entire array 

4579 had to be C-contiguous. 

4580 

4581 Examples 

4582 -------- 

4583 >>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)]) 

4584 

4585 Viewing array data using a different type and dtype: 

4586 

4587 >>> y = x.view(dtype=np.int16, type=np.matrix) 

4588 >>> y 

4589 matrix([[513]], dtype=int16) 

4590 >>> print(type(y)) 

4591 <class 'numpy.matrix'> 

4592 

4593 Creating a view on a structured array so it can be used in calculations 

4594 

4595 >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)]) 

4596 >>> xv = x.view(dtype=np.int8).reshape(-1,2) 

4597 >>> xv 

4598 array([[1, 2], 

4599 [3, 4]], dtype=int8) 

4600 >>> xv.mean(0) 

4601 array([2., 3.]) 

4602 

4603 Making changes to the view changes the underlying array 

4604 

4605 >>> xv[0,1] = 20 

4606 >>> x 

4607 array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')]) 

4608 

4609 Using a view to convert an array to a recarray: 

4610 

4611 >>> z = x.view(np.recarray) 

4612 >>> z.a 

4613 array([1, 3], dtype=int8) 

4614 

4615 Views share data: 

4616 

4617 >>> x[0] = (9, 10) 

4618 >>> z[0] 

4619 np.record((9, 10), dtype=[('a', 'i1'), ('b', 'i1')]) 

4620 

4621 Views that change the dtype size (bytes per entry) should normally be 

4622 avoided on arrays defined by slices, transposes, fortran-ordering, etc.: 

4623 

4624 >>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16) 

4625 >>> y = x[:, ::2] 

4626 >>> y 

4627 array([[1, 3], 

4628 [4, 6]], dtype=int16) 

4629 >>> y.view(dtype=[('width', np.int16), ('length', np.int16)]) 

4630 Traceback (most recent call last): 

4631 ... 

4632 ValueError: To change to a dtype of a different size, the last axis must be contiguous 

4633 >>> z = y.copy() 

4634 >>> z.view(dtype=[('width', np.int16), ('length', np.int16)]) 

4635 array([[(1, 3)], 

4636 [(4, 6)]], dtype=[('width', '<i2'), ('length', '<i2')]) 

4637 

4638 However, views that change dtype are totally fine for arrays with a 

4639 contiguous last axis, even if the rest of the axes are not C-contiguous: 

4640 

4641 >>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4) 

4642 >>> x.transpose(1, 0, 2).view(np.int16) 

4643 array([[[ 256, 770], 

4644 [3340, 3854]], 

4645 <BLANKLINE> 

4646 [[1284, 1798], 

4647 [4368, 4882]], 

4648 <BLANKLINE> 

4649 [[2312, 2826], 

4650 [5396, 5910]]], dtype=int16) 

4651 

4652 """)) 

4653 

4654 

4655############################################################################## 

4656# 

4657# umath functions 

4658# 

4659############################################################################## 

4660 

4661add_newdoc('numpy._core.umath', 'frompyfunc', 

4662 """ 

4663 frompyfunc(func, /, nin, nout, *[, identity]) 

4664 

4665 Takes an arbitrary Python function and returns a NumPy ufunc. 

4666 

4667 Can be used, for example, to add broadcasting to a built-in Python 

4668 function (see Examples section). 

4669 

4670 Parameters 

4671 ---------- 

4672 func : Python function object 

4673 An arbitrary Python function. 

4674 nin : int 

4675 The number of input arguments. 

4676 nout : int 

4677 The number of objects returned by `func`. 

4678 identity : object, optional 

4679 The value to use for the `~numpy.ufunc.identity` attribute of the resulting 

4680 object. If specified, this is equivalent to setting the underlying 

4681 C ``identity`` field to ``PyUFunc_IdentityValue``. 

4682 If omitted, the identity is set to ``PyUFunc_None``. Note that this is 

4683 _not_ equivalent to setting the identity to ``None``, which implies the 

4684 operation is reorderable. 

4685 

4686 Returns 

4687 ------- 

4688 out : ufunc 

4689 Returns a NumPy universal function (``ufunc``) object. 

4690 

4691 See Also 

4692 -------- 

4693 vectorize : Evaluates pyfunc over input arrays using broadcasting rules of numpy. 

4694 

4695 Notes 

4696 ----- 

4697 The returned ufunc always returns PyObject arrays. 

4698 

4699 Examples 

4700 -------- 

4701 Use frompyfunc to add broadcasting to the Python function ``oct``: 

4702 

4703 >>> oct_array = np.frompyfunc(oct, 1, 1) 

4704 >>> oct_array(np.array((10, 30, 100))) 

4705 array(['0o12', '0o36', '0o144'], dtype=object) 

4706 >>> np.array((oct(10), oct(30), oct(100))) # for comparison 

4707 array(['0o12', '0o36', '0o144'], dtype='<U5') 

4708 

4709 """) 

4710 

4711 

4712############################################################################## 

4713# 

4714# compiled_base functions 

4715# 

4716############################################################################## 

4717 

4718add_newdoc('numpy._core.multiarray', 'add_docstring', 

4719 """ 

4720 add_docstring(obj, docstring) 

4721 

4722 Add a docstring to a built-in obj if possible. 

4723 If the obj already has a docstring raise a RuntimeError 

4724 If this routine does not know how to add a docstring to the object 

4725 raise a TypeError 

4726 """) 

4727 

4728add_newdoc('numpy._core.umath', '_add_newdoc_ufunc', 

4729 """ 

4730 add_ufunc_docstring(ufunc, new_docstring) 

4731 

4732 Replace the docstring for a ufunc with new_docstring. 

4733 This method will only work if the current docstring for 

4734 the ufunc is NULL. (At the C level, i.e. when ufunc->doc is NULL.) 

4735 

4736 Parameters 

4737 ---------- 

4738 ufunc : numpy.ufunc 

4739 A ufunc whose current doc is NULL. 

4740 new_docstring : string 

4741 The new docstring for the ufunc. 

4742 

4743 Notes 

4744 ----- 

4745 This method allocates memory for new_docstring on 

4746 the heap. Technically this creates a memory leak, since this 

4747 memory will not be reclaimed until the end of the program 

4748 even if the ufunc itself is removed. However this will only 

4749 be a problem if the user is repeatedly creating ufuncs with 

4750 no documentation, adding documentation via add_newdoc_ufunc, 

4751 and then throwing away the ufunc. 

4752 """) 

4753 

4754add_newdoc('numpy._core.multiarray', 'get_handler_name', 

4755 """ 

4756 get_handler_name(a: ndarray) -> str,None 

4757 

4758 Return the name of the memory handler used by `a`. If not provided, return 

4759 the name of the memory handler that will be used to allocate data for the 

4760 next `ndarray` in this context. May return None if `a` does not own its 

4761 memory, in which case you can traverse ``a.base`` for a memory handler. 

4762 """) 

4763 

4764add_newdoc('numpy._core.multiarray', 'get_handler_version', 

4765 """ 

4766 get_handler_version(a: ndarray) -> int,None 

4767 

4768 Return the version of the memory handler used by `a`. If not provided, 

4769 return the version of the memory handler that will be used to allocate data 

4770 for the next `ndarray` in this context. May return None if `a` does not own 

4771 its memory, in which case you can traverse ``a.base`` for a memory handler. 

4772 """) 

4773 

4774add_newdoc('numpy._core._multiarray_umath', '_array_converter', 

4775 """ 

4776 _array_converter(*array_likes) 

4777 

4778 Helper to convert one or more objects to arrays. Integrates machinery 

4779 to deal with the ``result_type`` and ``__array_wrap__``. 

4780 

4781 The reason for this is that e.g. ``result_type`` needs to convert to arrays 

4782 to find the ``dtype``. But converting to an array before calling 

4783 ``result_type`` would incorrectly "forget" whether it was a Python int, 

4784 float, or complex. 

4785 """) 

4786 

4787add_newdoc( 

4788 'numpy._core._multiarray_umath', '_array_converter', ('scalar_input', 

4789 """ 

4790 A tuple which indicates for each input whether it was a scalar that 

4791 was coerced to a 0-D array (and was not already an array or something 

4792 converted via a protocol like ``__array__()``). 

4793 """)) 

4794 

4795add_newdoc('numpy._core._multiarray_umath', '_array_converter', ('as_arrays', 

4796 """ 

4797 as_arrays(/, subok=True, pyscalars="convert_if_no_array") 

4798 

4799 Return the inputs as arrays or scalars. 

4800 

4801 Parameters 

4802 ---------- 

4803 subok : True or False, optional 

4804 Whether array subclasses are preserved. 

4805 pyscalars : {"convert", "preserve", "convert_if_no_array"}, optional 

4806 To allow NEP 50 weak promotion later, it may be desirable to preserve 

4807 Python scalars. As default, these are preserved unless all inputs 

4808 are Python scalars. "convert" enforces an array return. 

4809 """)) 

4810 

4811add_newdoc('numpy._core._multiarray_umath', '_array_converter', ('result_type', 

4812 """result_type(/, extra_dtype=None, ensure_inexact=False) 

4813 

4814 Find the ``result_type`` just as ``np.result_type`` would, but taking 

4815 into account that the original inputs (before converting to an array) may 

4816 have been Python scalars with weak promotion. 

4817 

4818 Parameters 

4819 ---------- 

4820 extra_dtype : dtype instance or class 

4821 An additional DType or dtype instance to promote (e.g. could be used 

4822 to ensure the result precision is at least float32). 

4823 ensure_inexact : True or False 

4824 When ``True``, ensures a floating point (or complex) result replacing 

4825 the ``arr * 1.`` or ``result_type(..., 0.0)`` pattern. 

4826 """)) 

4827 

4828add_newdoc('numpy._core._multiarray_umath', '_array_converter', ('wrap', 

4829 """ 

4830 wrap(arr, /, to_scalar=None) 

4831 

4832 Call ``__array_wrap__`` on ``arr`` if ``arr`` is not the same subclass 

4833 as the input the ``__array_wrap__`` method was retrieved from. 

4834 

4835 Parameters 

4836 ---------- 

4837 arr : ndarray 

4838 The object to be wrapped. Normally an ndarray or subclass, 

4839 although for backward compatibility NumPy scalars are also accepted 

4840 (these will be converted to a NumPy array before being passed on to 

4841 the ``__array_wrap__`` method). 

4842 to_scalar : {True, False, None}, optional 

4843 When ``True`` will convert a 0-d array to a scalar via ``result[()]`` 

4844 (with a fast-path for non-subclasses). If ``False`` the result should 

4845 be an array-like (as ``__array_wrap__`` is free to return a non-array). 

4846 By default (``None``), a scalar is returned if all inputs were scalar. 

4847 """)) 

4848 

4849 

4850add_newdoc('numpy._core.multiarray', '_get_madvise_hugepage', 

4851 """ 

4852 _get_madvise_hugepage() -> bool 

4853 

4854 Get use of ``madvise (2)`` MADV_HUGEPAGE support when 

4855 allocating the array data. Returns the currently set value. 

4856 See `global_state` for more information. 

4857 """) 

4858 

4859add_newdoc('numpy._core.multiarray', '_set_madvise_hugepage', 

4860 """ 

4861 _set_madvise_hugepage(enabled: bool) -> bool 

4862 

4863 Set or unset use of ``madvise (2)`` MADV_HUGEPAGE support when 

4864 allocating the array data. Returns the previously set value. 

4865 See `global_state` for more information. 

4866 """) 

4867 

4868add_newdoc('numpy._core._multiarray_tests', 'format_float_OSprintf_g', 

4869 """ 

4870 format_float_OSprintf_g(val, precision) 

4871 

4872 Print a floating point scalar using the system's printf function, 

4873 equivalent to: 

4874 

4875 printf("%.*g", precision, val); 

4876 

4877 for half/float/double, or replacing 'g' by 'Lg' for longdouble. This 

4878 method is designed to help cross-validate the format_float_* methods. 

4879 

4880 Parameters 

4881 ---------- 

4882 val : python float or numpy floating scalar 

4883 Value to format. 

4884 

4885 precision : non-negative integer, optional 

4886 Precision given to printf. 

4887 

4888 Returns 

4889 ------- 

4890 rep : string 

4891 The string representation of the floating point value 

4892 

4893 See Also 

4894 -------- 

4895 format_float_scientific 

4896 format_float_positional 

4897 """) 

4898 

4899 

4900############################################################################## 

4901# 

4902# Documentation for ufunc attributes and methods 

4903# 

4904############################################################################## 

4905 

4906 

4907############################################################################## 

4908# 

4909# ufunc object 

4910# 

4911############################################################################## 

4912 

4913add_newdoc('numpy._core', 'ufunc', 

4914 """ 

4915 Functions that operate element by element on whole arrays. 

4916 

4917 To see the documentation for a specific ufunc, use `info`. For 

4918 example, ``np.info(np.sin)``. Because ufuncs are written in C 

4919 (for speed) and linked into Python with NumPy's ufunc facility, 

4920 Python's help() function finds this page whenever help() is called 

4921 on a ufunc. 

4922 

4923 A detailed explanation of ufuncs can be found in the docs for :ref:`ufuncs`. 

4924 

4925 **Calling ufuncs:** ``op(*x[, out], where=True, **kwargs)`` 

4926 

4927 Apply `op` to the arguments `*x` elementwise, broadcasting the arguments. 

4928 

4929 The broadcasting rules are: 

4930 

4931 * Dimensions of length 1 may be prepended to either array. 

4932 * Arrays may be repeated along dimensions of length 1. 

4933 

4934 Parameters 

4935 ---------- 

4936 *x : array_like 

4937 Input arrays. 

4938 out : ndarray, None, or tuple of ndarray and None, optional 

4939 Alternate array object(s) in which to put the result; if provided, it 

4940 must have a shape that the inputs broadcast to. A tuple of arrays 

4941 (possible only as a keyword argument) must have length equal to the 

4942 number of outputs; use None for uninitialized outputs to be 

4943 allocated by the ufunc. 

4944 where : array_like, optional 

4945 This condition is broadcast over the input. At locations where the 

4946 condition is True, the `out` array will be set to the ufunc result. 

4947 Elsewhere, the `out` array will retain its original value. 

4948 Note that if an uninitialized `out` array is created via the default 

4949 ``out=None``, locations within it where the condition is False will 

4950 remain uninitialized. 

4951 **kwargs 

4952 For other keyword-only arguments, see the :ref:`ufunc docs <ufuncs.kwargs>`. 

4953 

4954 Returns 

4955 ------- 

4956 r : ndarray or tuple of ndarray 

4957 `r` will have the shape that the arrays in `x` broadcast to; if `out` is 

4958 provided, it will be returned. If not, `r` will be allocated and 

4959 may contain uninitialized values. If the function has more than one 

4960 output, then the result will be a tuple of arrays. 

4961 

4962 """) 

4963 

4964 

4965############################################################################## 

4966# 

4967# ufunc attributes 

4968# 

4969############################################################################## 

4970 

4971add_newdoc('numpy._core', 'ufunc', ('identity', 

4972 """ 

4973 The identity value. 

4974 

4975 Data attribute containing the identity element for the ufunc, 

4976 if it has one. If it does not, the attribute value is None. 

4977 

4978 Examples 

4979 -------- 

4980 >>> np.add.identity 

4981 0 

4982 >>> np.multiply.identity 

4983 1 

4984 >>> np.power.identity 

4985 1 

4986 >>> print(np.exp.identity) 

4987 None 

4988 """)) 

4989 

4990add_newdoc('numpy._core', 'ufunc', ('nargs', 

4991 """ 

4992 The number of arguments. 

4993 

4994 Data attribute containing the number of arguments the ufunc takes, including 

4995 optional ones. 

4996 

4997 Notes 

4998 ----- 

4999 Typically this value will be one more than what you might expect 

5000 because all ufuncs take the optional "out" argument. 

5001 

5002 Examples 

5003 -------- 

5004 >>> np.add.nargs 

5005 3 

5006 >>> np.multiply.nargs 

5007 3 

5008 >>> np.power.nargs 

5009 3 

5010 >>> np.exp.nargs 

5011 2 

5012 """)) 

5013 

5014add_newdoc('numpy._core', 'ufunc', ('nin', 

5015 """ 

5016 The number of inputs. 

5017 

5018 Data attribute containing the number of arguments the ufunc treats as input. 

5019 

5020 Examples 

5021 -------- 

5022 >>> np.add.nin 

5023 2 

5024 >>> np.multiply.nin 

5025 2 

5026 >>> np.power.nin 

5027 2 

5028 >>> np.exp.nin 

5029 1 

5030 """)) 

5031 

5032add_newdoc('numpy._core', 'ufunc', ('nout', 

5033 """ 

5034 The number of outputs. 

5035 

5036 Data attribute containing the number of arguments the ufunc treats as output. 

5037 

5038 Notes 

5039 ----- 

5040 Since all ufuncs can take output arguments, this will always be at least 1. 

5041 

5042 Examples 

5043 -------- 

5044 >>> np.add.nout 

5045 1 

5046 >>> np.multiply.nout 

5047 1 

5048 >>> np.power.nout 

5049 1 

5050 >>> np.exp.nout 

5051 1 

5052 

5053 """)) 

5054 

5055add_newdoc('numpy._core', 'ufunc', ('ntypes', 

5056 """ 

5057 The number of types. 

5058 

5059 The number of numerical NumPy types - of which there are 18 total - on which 

5060 the ufunc can operate. 

5061 

5062 See Also 

5063 -------- 

5064 numpy.ufunc.types 

5065 

5066 Examples 

5067 -------- 

5068 >>> np.add.ntypes 

5069 18 

5070 >>> np.multiply.ntypes 

5071 18 

5072 >>> np.power.ntypes 

5073 17 

5074 >>> np.exp.ntypes 

5075 7 

5076 >>> np.remainder.ntypes 

5077 14 

5078 

5079 """)) 

5080 

5081add_newdoc('numpy._core', 'ufunc', ('types', 

5082 """ 

5083 Returns a list with types grouped input->output. 

5084 

5085 Data attribute listing the data-type "Domain-Range" groupings the ufunc can 

5086 deliver. The data-types are given using the character codes. 

5087 

5088 See Also 

5089 -------- 

5090 numpy.ufunc.ntypes 

5091 

5092 Examples 

5093 -------- 

5094 >>> np.add.types 

5095 ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 

5096 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 

5097 'GG->G', 'OO->O'] 

5098 

5099 >>> np.multiply.types 

5100 ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 

5101 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 

5102 'GG->G', 'OO->O'] 

5103 

5104 >>> np.power.types 

5105 ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 

5106 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G', 

5107 'OO->O'] 

5108 

5109 >>> np.exp.types 

5110 ['f->f', 'd->d', 'g->g', 'F->F', 'D->D', 'G->G', 'O->O'] 

5111 

5112 >>> np.remainder.types 

5113 ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 

5114 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'OO->O'] 

5115 

5116 """)) 

5117 

5118add_newdoc('numpy._core', 'ufunc', ('signature', 

5119 """ 

5120 Definition of the core elements a generalized ufunc operates on. 

5121 

5122 The signature determines how the dimensions of each input/output array 

5123 are split into core and loop dimensions: 

5124 

5125 1. Each dimension in the signature is matched to a dimension of the 

5126 corresponding passed-in array, starting from the end of the shape tuple. 

5127 2. Core dimensions assigned to the same label in the signature must have 

5128 exactly matching sizes, no broadcasting is performed. 

5129 3. The core dimensions are removed from all inputs and the remaining 

5130 dimensions are broadcast together, defining the loop dimensions. 

5131 

5132 Notes 

5133 ----- 

5134 Generalized ufuncs are used internally in many linalg functions, and in 

5135 the testing suite; the examples below are taken from these. 

5136 For ufuncs that operate on scalars, the signature is None, which is 

5137 equivalent to '()' for every argument. 

5138 

5139 Examples 

5140 -------- 

5141 >>> np.linalg._umath_linalg.det.signature 

5142 '(m,m)->()' 

5143 >>> np.matmul.signature 

5144 '(n?,k),(k,m?)->(n?,m?)' 

5145 >>> np.add.signature is None 

5146 True # equivalent to '(),()->()' 

5147 """)) 

5148 

5149############################################################################## 

5150# 

5151# ufunc methods 

5152# 

5153############################################################################## 

5154 

5155add_newdoc('numpy._core', 'ufunc', ('reduce', 

5156 """ 

5157 reduce(array, axis=0, dtype=None, out=None, keepdims=False, initial=<no value>, where=True) 

5158 

5159 Reduces `array`'s dimension by one, by applying ufunc along one axis. 

5160 

5161 Let :math:`array.shape = (N_0, ..., N_i, ..., N_{M-1})`. Then 

5162 :math:`ufunc.reduce(array, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}]` = 

5163 the result of iterating `j` over :math:`range(N_i)`, cumulatively applying 

5164 ufunc to each :math:`array[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]`. 

5165 For a one-dimensional array, reduce produces results equivalent to: 

5166 :: 

5167 

5168 r = op.identity # op = ufunc 

5169 for i in range(len(A)): 

5170 r = op(r, A[i]) 

5171 return r 

5172 

5173 For example, add.reduce() is equivalent to sum(). 

5174 

5175 Parameters 

5176 ---------- 

5177 array : array_like 

5178 The array to act on. 

5179 axis : None or int or tuple of ints, optional 

5180 Axis or axes along which a reduction is performed. 

5181 The default (`axis` = 0) is perform a reduction over the first 

5182 dimension of the input array. `axis` may be negative, in 

5183 which case it counts from the last to the first axis. 

5184 

5185 .. versionadded:: 1.7.0 

5186 

5187 If this is None, a reduction is performed over all the axes. 

5188 If this is a tuple of ints, a reduction is performed on multiple 

5189 axes, instead of a single axis or all the axes as before. 

5190 

5191 For operations which are either not commutative or not associative, 

5192 doing a reduction over multiple axes is not well-defined. The 

5193 ufuncs do not currently raise an exception in this case, but will 

5194 likely do so in the future. 

5195 dtype : data-type code, optional 

5196 The data type used to perform the operation. Defaults to that of 

5197 ``out`` if given, and the data type of ``array`` otherwise (though 

5198 upcast to conserve precision for some cases, such as 

5199 ``numpy.add.reduce`` for integer or boolean input). 

5200 out : ndarray, None, or tuple of ndarray and None, optional 

5201 A location into which the result is stored. If not provided or None, 

5202 a freshly-allocated array is returned. For consistency with 

5203 ``ufunc.__call__``, if given as a keyword, this may be wrapped in a 

5204 1-element tuple. 

5205 

5206 .. versionchanged:: 1.13.0 

5207 Tuples are allowed for keyword argument. 

5208 keepdims : bool, optional 

5209 If this is set to True, the axes which are reduced are left 

5210 in the result as dimensions with size one. With this option, 

5211 the result will broadcast correctly against the original `array`. 

5212 

5213 .. versionadded:: 1.7.0 

5214 initial : scalar, optional 

5215 The value with which to start the reduction. 

5216 If the ufunc has no identity or the dtype is object, this defaults 

5217 to None - otherwise it defaults to ufunc.identity. 

5218 If ``None`` is given, the first element of the reduction is used, 

5219 and an error is thrown if the reduction is empty. 

5220 

5221 .. versionadded:: 1.15.0 

5222 

5223 where : array_like of bool, optional 

5224 A boolean array which is broadcasted to match the dimensions 

5225 of `array`, and selects elements to include in the reduction. Note 

5226 that for ufuncs like ``minimum`` that do not have an identity 

5227 defined, one has to pass in also ``initial``. 

5228 

5229 .. versionadded:: 1.17.0 

5230 

5231 Returns 

5232 ------- 

5233 r : ndarray 

5234 The reduced array. If `out` was supplied, `r` is a reference to it. 

5235 

5236 Examples 

5237 -------- 

5238 >>> np.multiply.reduce([2,3,5]) 

5239 30 

5240 

5241 A multi-dimensional array example: 

5242 

5243 >>> X = np.arange(8).reshape((2,2,2)) 

5244 >>> X 

5245 array([[[0, 1], 

5246 [2, 3]], 

5247 [[4, 5], 

5248 [6, 7]]]) 

5249 >>> np.add.reduce(X, 0) 

5250 array([[ 4, 6], 

5251 [ 8, 10]]) 

5252 >>> np.add.reduce(X) # confirm: default axis value is 0 

5253 array([[ 4, 6], 

5254 [ 8, 10]]) 

5255 >>> np.add.reduce(X, 1) 

5256 array([[ 2, 4], 

5257 [10, 12]]) 

5258 >>> np.add.reduce(X, 2) 

5259 array([[ 1, 5], 

5260 [ 9, 13]]) 

5261 

5262 You can use the ``initial`` keyword argument to initialize the reduction 

5263 with a different value, and ``where`` to select specific elements to include: 

5264 

5265 >>> np.add.reduce([10], initial=5) 

5266 15 

5267 >>> np.add.reduce(np.ones((2, 2, 2)), axis=(0, 2), initial=10) 

5268 array([14., 14.]) 

5269 >>> a = np.array([10., np.nan, 10]) 

5270 >>> np.add.reduce(a, where=~np.isnan(a)) 

5271 20.0 

5272 

5273 Allows reductions of empty arrays where they would normally fail, i.e. 

5274 for ufuncs without an identity. 

5275 

5276 >>> np.minimum.reduce([], initial=np.inf) 

5277 inf 

5278 >>> np.minimum.reduce([[1., 2.], [3., 4.]], initial=10., where=[True, False]) 

5279 array([ 1., 10.]) 

5280 >>> np.minimum.reduce([]) 

5281 Traceback (most recent call last): 

5282 ... 

5283 ValueError: zero-size array to reduction operation minimum which has no identity 

5284 """)) 

5285 

5286add_newdoc('numpy._core', 'ufunc', ('accumulate', 

5287 """ 

5288 accumulate(array, axis=0, dtype=None, out=None) 

5289 

5290 Accumulate the result of applying the operator to all elements. 

5291 

5292 For a one-dimensional array, accumulate produces results equivalent to:: 

5293 

5294 r = np.empty(len(A)) 

5295 t = op.identity # op = the ufunc being applied to A's elements 

5296 for i in range(len(A)): 

5297 t = op(t, A[i]) 

5298 r[i] = t 

5299 return r 

5300 

5301 For example, add.accumulate() is equivalent to np.cumsum(). 

5302 

5303 For a multi-dimensional array, accumulate is applied along only one 

5304 axis (axis zero by default; see Examples below) so repeated use is 

5305 necessary if one wants to accumulate over multiple axes. 

5306 

5307 Parameters 

5308 ---------- 

5309 array : array_like 

5310 The array to act on. 

5311 axis : int, optional 

5312 The axis along which to apply the accumulation; default is zero. 

5313 dtype : data-type code, optional 

5314 The data-type used to represent the intermediate results. Defaults 

5315 to the data-type of the output array if such is provided, or the 

5316 data-type of the input array if no output array is provided. 

5317 out : ndarray, None, or tuple of ndarray and None, optional 

5318 A location into which the result is stored. If not provided or None, 

5319 a freshly-allocated array is returned. For consistency with 

5320 ``ufunc.__call__``, if given as a keyword, this may be wrapped in a 

5321 1-element tuple. 

5322 

5323 .. versionchanged:: 1.13.0 

5324 Tuples are allowed for keyword argument. 

5325 

5326 Returns 

5327 ------- 

5328 r : ndarray 

5329 The accumulated values. If `out` was supplied, `r` is a reference to 

5330 `out`. 

5331 

5332 Examples 

5333 -------- 

5334 1-D array examples: 

5335 

5336 >>> np.add.accumulate([2, 3, 5]) 

5337 array([ 2, 5, 10]) 

5338 >>> np.multiply.accumulate([2, 3, 5]) 

5339 array([ 2, 6, 30]) 

5340 

5341 2-D array examples: 

5342 

5343 >>> I = np.eye(2) 

5344 >>> I 

5345 array([[1., 0.], 

5346 [0., 1.]]) 

5347 

5348 Accumulate along axis 0 (rows), down columns: 

5349 

5350 >>> np.add.accumulate(I, 0) 

5351 array([[1., 0.], 

5352 [1., 1.]]) 

5353 >>> np.add.accumulate(I) # no axis specified = axis zero 

5354 array([[1., 0.], 

5355 [1., 1.]]) 

5356 

5357 Accumulate along axis 1 (columns), through rows: 

5358 

5359 >>> np.add.accumulate(I, 1) 

5360 array([[1., 1.], 

5361 [0., 1.]]) 

5362 

5363 """)) 

5364 

5365add_newdoc('numpy._core', 'ufunc', ('reduceat', 

5366 """ 

5367 reduceat(array, indices, axis=0, dtype=None, out=None) 

5368 

5369 Performs a (local) reduce with specified slices over a single axis. 

5370 

5371 For i in ``range(len(indices))``, `reduceat` computes 

5372 ``ufunc.reduce(array[indices[i]:indices[i+1]])``, which becomes the i-th 

5373 generalized "row" parallel to `axis` in the final result (i.e., in a 

5374 2-D array, for example, if `axis = 0`, it becomes the i-th row, but if 

5375 `axis = 1`, it becomes the i-th column). There are three exceptions to this: 

5376 

5377 * when ``i = len(indices) - 1`` (so for the last index), 

5378 ``indices[i+1] = array.shape[axis]``. 

5379 * if ``indices[i] >= indices[i + 1]``, the i-th generalized "row" is 

5380 simply ``array[indices[i]]``. 

5381 * if ``indices[i] >= len(array)`` or ``indices[i] < 0``, an error is raised. 

5382 

5383 The shape of the output depends on the size of `indices`, and may be 

5384 larger than `array` (this happens if ``len(indices) > array.shape[axis]``). 

5385 

5386 Parameters 

5387 ---------- 

5388 array : array_like 

5389 The array to act on. 

5390 indices : array_like 

5391 Paired indices, comma separated (not colon), specifying slices to 

5392 reduce. 

5393 axis : int, optional 

5394 The axis along which to apply the reduceat. 

5395 dtype : data-type code, optional 

5396 The data type used to perform the operation. Defaults to that of 

5397 ``out`` if given, and the data type of ``array`` otherwise (though 

5398 upcast to conserve precision for some cases, such as 

5399 ``numpy.add.reduce`` for integer or boolean input). 

5400 out : ndarray, None, or tuple of ndarray and None, optional 

5401 A location into which the result is stored. If not provided or None, 

5402 a freshly-allocated array is returned. For consistency with 

5403 ``ufunc.__call__``, if given as a keyword, this may be wrapped in a 

5404 1-element tuple. 

5405 

5406 .. versionchanged:: 1.13.0 

5407 Tuples are allowed for keyword argument. 

5408 

5409 Returns 

5410 ------- 

5411 r : ndarray 

5412 The reduced values. If `out` was supplied, `r` is a reference to 

5413 `out`. 

5414 

5415 Notes 

5416 ----- 

5417 A descriptive example: 

5418 

5419 If `array` is 1-D, the function `ufunc.accumulate(array)` is the same as 

5420 ``ufunc.reduceat(array, indices)[::2]`` where `indices` is 

5421 ``range(len(array) - 1)`` with a zero placed 

5422 in every other element: 

5423 ``indices = zeros(2 * len(array) - 1)``, 

5424 ``indices[1::2] = range(1, len(array))``. 

5425 

5426 Don't be fooled by this attribute's name: `reduceat(array)` is not 

5427 necessarily smaller than `array`. 

5428 

5429 Examples 

5430 -------- 

5431 To take the running sum of four successive values: 

5432 

5433 >>> np.add.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2] 

5434 array([ 6, 10, 14, 18]) 

5435 

5436 A 2-D example: 

5437 

5438 >>> x = np.linspace(0, 15, 16).reshape(4,4) 

5439 >>> x 

5440 array([[ 0., 1., 2., 3.], 

5441 [ 4., 5., 6., 7.], 

5442 [ 8., 9., 10., 11.], 

5443 [12., 13., 14., 15.]]) 

5444 

5445 :: 

5446 

5447 # reduce such that the result has the following five rows: 

5448 # [row1 + row2 + row3] 

5449 # [row4] 

5450 # [row2] 

5451 # [row3] 

5452 # [row1 + row2 + row3 + row4] 

5453 

5454 >>> np.add.reduceat(x, [0, 3, 1, 2, 0]) 

5455 array([[12., 15., 18., 21.], 

5456 [12., 13., 14., 15.], 

5457 [ 4., 5., 6., 7.], 

5458 [ 8., 9., 10., 11.], 

5459 [24., 28., 32., 36.]]) 

5460 

5461 :: 

5462 

5463 # reduce such that result has the following two columns: 

5464 # [col1 * col2 * col3, col4] 

5465 

5466 >>> np.multiply.reduceat(x, [0, 3], 1) 

5467 array([[ 0., 3.], 

5468 [ 120., 7.], 

5469 [ 720., 11.], 

5470 [2184., 15.]]) 

5471 

5472 """)) 

5473 

5474add_newdoc('numpy._core', 'ufunc', ('outer', 

5475 r""" 

5476 outer(A, B, /, **kwargs) 

5477 

5478 Apply the ufunc `op` to all pairs (a, b) with a in `A` and b in `B`. 

5479 

5480 Let ``M = A.ndim``, ``N = B.ndim``. Then the result, `C`, of 

5481 ``op.outer(A, B)`` is an array of dimension M + N such that: 

5482 

5483 .. math:: C[i_0, ..., i_{M-1}, j_0, ..., j_{N-1}] = 

5484 op(A[i_0, ..., i_{M-1}], B[j_0, ..., j_{N-1}]) 

5485 

5486 For `A` and `B` one-dimensional, this is equivalent to:: 

5487 

5488 r = empty(len(A),len(B)) 

5489 for i in range(len(A)): 

5490 for j in range(len(B)): 

5491 r[i,j] = op(A[i], B[j]) # op = ufunc in question 

5492 

5493 Parameters 

5494 ---------- 

5495 A : array_like 

5496 First array 

5497 B : array_like 

5498 Second array 

5499 kwargs : any 

5500 Arguments to pass on to the ufunc. Typically `dtype` or `out`. 

5501 See `ufunc` for a comprehensive overview of all available arguments. 

5502 

5503 Returns 

5504 ------- 

5505 r : ndarray 

5506 Output array 

5507 

5508 See Also 

5509 -------- 

5510 numpy.outer : A less powerful version of ``np.multiply.outer`` 

5511 that `ravel`\ s all inputs to 1D. This exists 

5512 primarily for compatibility with old code. 

5513 

5514 tensordot : ``np.tensordot(a, b, axes=((), ()))`` and 

5515 ``np.multiply.outer(a, b)`` behave same for all 

5516 dimensions of a and b. 

5517 

5518 Examples 

5519 -------- 

5520 >>> np.multiply.outer([1, 2, 3], [4, 5, 6]) 

5521 array([[ 4, 5, 6], 

5522 [ 8, 10, 12], 

5523 [12, 15, 18]]) 

5524 

5525 A multi-dimensional example: 

5526 

5527 >>> A = np.array([[1, 2, 3], [4, 5, 6]]) 

5528 >>> A.shape 

5529 (2, 3) 

5530 >>> B = np.array([[1, 2, 3, 4]]) 

5531 >>> B.shape 

5532 (1, 4) 

5533 >>> C = np.multiply.outer(A, B) 

5534 >>> C.shape; C 

5535 (2, 3, 1, 4) 

5536 array([[[[ 1, 2, 3, 4]], 

5537 [[ 2, 4, 6, 8]], 

5538 [[ 3, 6, 9, 12]]], 

5539 [[[ 4, 8, 12, 16]], 

5540 [[ 5, 10, 15, 20]], 

5541 [[ 6, 12, 18, 24]]]]) 

5542 

5543 """)) 

5544 

5545add_newdoc('numpy._core', 'ufunc', ('at', 

5546 """ 

5547 at(a, indices, b=None, /) 

5548 

5549 Performs unbuffered in place operation on operand 'a' for elements 

5550 specified by 'indices'. For addition ufunc, this method is equivalent to 

5551 ``a[indices] += b``, except that results are accumulated for elements that 

5552 are indexed more than once. For example, ``a[[0,0]] += 1`` will only 

5553 increment the first element once because of buffering, whereas 

5554 ``add.at(a, [0,0], 1)`` will increment the first element twice. 

5555 

5556 .. versionadded:: 1.8.0 

5557 

5558 Parameters 

5559 ---------- 

5560 a : array_like 

5561 The array to perform in place operation on. 

5562 indices : array_like or tuple 

5563 Array like index object or slice object for indexing into first 

5564 operand. If first operand has multiple dimensions, indices can be a 

5565 tuple of array like index objects or slice objects. 

5566 b : array_like 

5567 Second operand for ufuncs requiring two operands. Operand must be 

5568 broadcastable over first operand after indexing or slicing. 

5569 

5570 Examples 

5571 -------- 

5572 Set items 0 and 1 to their negative values: 

5573 

5574 >>> a = np.array([1, 2, 3, 4]) 

5575 >>> np.negative.at(a, [0, 1]) 

5576 >>> a 

5577 array([-1, -2, 3, 4]) 

5578 

5579 Increment items 0 and 1, and increment item 2 twice: 

5580 

5581 >>> a = np.array([1, 2, 3, 4]) 

5582 >>> np.add.at(a, [0, 1, 2, 2], 1) 

5583 >>> a 

5584 array([2, 3, 5, 4]) 

5585 

5586 Add items 0 and 1 in first array to second array, 

5587 and store results in first array: 

5588 

5589 >>> a = np.array([1, 2, 3, 4]) 

5590 >>> b = np.array([1, 2]) 

5591 >>> np.add.at(a, [0, 1], b) 

5592 >>> a 

5593 array([2, 4, 3, 4]) 

5594 

5595 """)) 

5596 

5597add_newdoc('numpy._core', 'ufunc', ('resolve_dtypes', 

5598 """ 

5599 resolve_dtypes(dtypes, *, signature=None, casting=None, reduction=False) 

5600 

5601 Find the dtypes NumPy will use for the operation. Both input and 

5602 output dtypes are returned and may differ from those provided. 

5603 

5604 .. note:: 

5605 

5606 This function always applies NEP 50 rules since it is not provided 

5607 any actual values. The Python types ``int``, ``float``, and 

5608 ``complex`` thus behave weak and should be passed for "untyped" 

5609 Python input. 

5610 

5611 Parameters 

5612 ---------- 

5613 dtypes : tuple of dtypes, None, or literal int, float, complex 

5614 The input dtypes for each operand. Output operands can be 

5615 None, indicating that the dtype must be found. 

5616 signature : tuple of DTypes or None, optional 

5617 If given, enforces exact DType (classes) of the specific operand. 

5618 The ufunc ``dtype`` argument is equivalent to passing a tuple with 

5619 only output dtypes set. 

5620 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional 

5621 The casting mode when casting is necessary. This is identical to 

5622 the ufunc call casting modes. 

5623 reduction : boolean 

5624 If given, the resolution assumes a reduce operation is happening 

5625 which slightly changes the promotion and type resolution rules. 

5626 `dtypes` is usually something like ``(None, np.dtype("i2"), None)`` 

5627 for reductions (first input is also the output). 

5628 

5629 .. note:: 

5630 

5631 The default casting mode is "same_kind", however, as of 

5632 NumPy 1.24, NumPy uses "unsafe" for reductions. 

5633 

5634 Returns 

5635 ------- 

5636 dtypes : tuple of dtypes 

5637 The dtypes which NumPy would use for the calculation. Note that 

5638 dtypes may not match the passed in ones (casting is necessary). 

5639 

5640 

5641 Examples 

5642 -------- 

5643 This API requires passing dtypes, define them for convenience: 

5644 

5645 >>> int32 = np.dtype("int32") 

5646 >>> float32 = np.dtype("float32") 

5647 

5648 The typical ufunc call does not pass an output dtype. `numpy.add` has two 

5649 inputs and one output, so leave the output as ``None`` (not provided): 

5650 

5651 >>> np.add.resolve_dtypes((int32, float32, None)) 

5652 (dtype('float64'), dtype('float64'), dtype('float64')) 

5653 

5654 The loop found uses "float64" for all operands (including the output), the 

5655 first input would be cast. 

5656 

5657 ``resolve_dtypes`` supports "weak" handling for Python scalars by passing 

5658 ``int``, ``float``, or ``complex``: 

5659 

5660 >>> np.add.resolve_dtypes((float32, float, None)) 

5661 (dtype('float32'), dtype('float32'), dtype('float32')) 

5662 

5663 Where the Python ``float`` behaves samilar to a Python value ``0.0`` 

5664 in a ufunc call. (See :ref:`NEP 50 <NEP50>` for details.) 

5665 

5666 """)) 

5667 

5668add_newdoc('numpy._core', 'ufunc', ('_resolve_dtypes_and_context', 

5669 """ 

5670 _resolve_dtypes_and_context(dtypes, *, signature=None, casting=None, reduction=False) 

5671 

5672 See `numpy.ufunc.resolve_dtypes` for parameter information. This 

5673 function is considered *unstable*. You may use it, but the returned 

5674 information is NumPy version specific and expected to change. 

5675 Large API/ABI changes are not expected, but a new NumPy version is 

5676 expected to require updating code using this functionality. 

5677 

5678 This function is designed to be used in conjunction with 

5679 `numpy.ufunc._get_strided_loop`. The calls are split to mirror the C API 

5680 and allow future improvements. 

5681 

5682 Returns 

5683 ------- 

5684 dtypes : tuple of dtypes 

5685 call_info : 

5686 PyCapsule with all necessary information to get access to low level 

5687 C calls. See `numpy.ufunc._get_strided_loop` for more information. 

5688 

5689 """)) 

5690 

5691add_newdoc('numpy._core', 'ufunc', ('_get_strided_loop', 

5692 """ 

5693 _get_strided_loop(call_info, /, *, fixed_strides=None) 

5694 

5695 This function fills in the ``call_info`` capsule to include all 

5696 information necessary to call the low-level strided loop from NumPy. 

5697 

5698 See notes for more information. 

5699 

5700 Parameters 

5701 ---------- 

5702 call_info : PyCapsule 

5703 The PyCapsule returned by `numpy.ufunc._resolve_dtypes_and_context`. 

5704 fixed_strides : tuple of int or None, optional 

5705 A tuple with fixed byte strides of all input arrays. NumPy may use 

5706 this information to find specialized loops, so any call must follow 

5707 the given stride. Use ``None`` to indicate that the stride is not 

5708 known (or not fixed) for all calls. 

5709 

5710 Notes 

5711 ----- 

5712 Together with `numpy.ufunc._resolve_dtypes_and_context` this function 

5713 gives low-level access to the NumPy ufunc loops. 

5714 The first function does general preparation and returns the required 

5715 information. It returns this as a C capsule with the version specific 

5716 name ``numpy_1.24_ufunc_call_info``. 

5717 The NumPy 1.24 ufunc call info capsule has the following layout:: 

5718 

5719 typedef struct { 

5720 PyArrayMethod_StridedLoop *strided_loop; 

5721 PyArrayMethod_Context *context; 

5722 NpyAuxData *auxdata; 

5723 

5724 /* Flag information (expected to change) */ 

5725 npy_bool requires_pyapi; /* GIL is required by loop */ 

5726 

5727 /* Loop doesn't set FPE flags; if not set check FPE flags */ 

5728 npy_bool no_floatingpoint_errors; 

5729 } ufunc_call_info; 

5730 

5731 Note that the first call only fills in the ``context``. The call to 

5732 ``_get_strided_loop`` fills in all other data. The main thing to note is 

5733 that the new-style loops return 0 on success, -1 on failure. They are 

5734 passed context as new first input and ``auxdata`` as (replaced) last. 

5735 

5736 Only the ``strided_loop``signature is considered guaranteed stable 

5737 for NumPy bug-fix releases. All other API is tied to the experimental 

5738 API versioning. 

5739 

5740 The reason for the split call is that cast information is required to 

5741 decide what the fixed-strides will be. 

5742 

5743 NumPy ties the lifetime of the ``auxdata`` information to the capsule. 

5744 

5745 """)) 

5746 

5747 

5748 

5749############################################################################## 

5750# 

5751# Documentation for dtype attributes and methods 

5752# 

5753############################################################################## 

5754 

5755############################################################################## 

5756# 

5757# dtype object 

5758# 

5759############################################################################## 

5760 

5761add_newdoc('numpy._core.multiarray', 'dtype', 

5762 """ 

5763 dtype(dtype, align=False, copy=False, [metadata]) 

5764 

5765 Create a data type object. 

5766 

5767 A numpy array is homogeneous, and contains elements described by a 

5768 dtype object. A dtype object can be constructed from different 

5769 combinations of fundamental numeric types. 

5770 

5771 Parameters 

5772 ---------- 

5773 dtype 

5774 Object to be converted to a data type object. 

5775 align : bool, optional 

5776 Add padding to the fields to match what a C compiler would output 

5777 for a similar C-struct. Can be ``True`` only if `obj` is a dictionary 

5778 or a comma-separated string. If a struct dtype is being created, 

5779 this also sets a sticky alignment flag ``isalignedstruct``. 

5780 copy : bool, optional 

5781 Make a new copy of the data-type object. If ``False``, the result 

5782 may just be a reference to a built-in data-type object. 

5783 metadata : dict, optional 

5784 An optional dictionary with dtype metadata. 

5785 

5786 See also 

5787 -------- 

5788 result_type 

5789 

5790 Examples 

5791 -------- 

5792 Using array-scalar type: 

5793 

5794 >>> np.dtype(np.int16) 

5795 dtype('int16') 

5796 

5797 Structured type, one field name 'f1', containing int16: 

5798 

5799 >>> np.dtype([('f1', np.int16)]) 

5800 dtype([('f1', '<i2')]) 

5801 

5802 Structured type, one field named 'f1', in itself containing a structured 

5803 type with one field: 

5804 

5805 >>> np.dtype([('f1', [('f1', np.int16)])]) 

5806 dtype([('f1', [('f1', '<i2')])]) 

5807 

5808 Structured type, two fields: the first field contains an unsigned int, the 

5809 second an int32: 

5810 

5811 >>> np.dtype([('f1', np.uint64), ('f2', np.int32)]) 

5812 dtype([('f1', '<u8'), ('f2', '<i4')]) 

5813 

5814 Using array-protocol type strings: 

5815 

5816 >>> np.dtype([('a','f8'),('b','S10')]) 

5817 dtype([('a', '<f8'), ('b', 'S10')]) 

5818 

5819 Using comma-separated field formats. The shape is (2,3): 

5820 

5821 >>> np.dtype("i4, (2,3)f8") 

5822 dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))]) 

5823 

5824 Using tuples. ``int`` is a fixed type, 3 the field's shape. ``void`` 

5825 is a flexible type, here of size 10: 

5826 

5827 >>> np.dtype([('hello',(np.int64,3)),('world',np.void,10)]) 

5828 dtype([('hello', '<i8', (3,)), ('world', 'V10')]) 

5829 

5830 Subdivide ``int16`` into 2 ``int8``'s, called x and y. 0 and 1 are 

5831 the offsets in bytes: 

5832 

5833 >>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)})) 

5834 dtype((numpy.int16, [('x', 'i1'), ('y', 'i1')])) 

5835 

5836 Using dictionaries. Two fields named 'gender' and 'age': 

5837 

5838 >>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]}) 

5839 dtype([('gender', 'S1'), ('age', 'u1')]) 

5840 

5841 Offsets in bytes, here 0 and 25: 

5842 

5843 >>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)}) 

5844 dtype([('surname', 'S25'), ('age', 'u1')]) 

5845 

5846 """) 

5847 

5848############################################################################## 

5849# 

5850# dtype attributes 

5851# 

5852############################################################################## 

5853 

5854add_newdoc('numpy._core.multiarray', 'dtype', ('alignment', 

5855 """ 

5856 The required alignment (bytes) of this data-type according to the compiler. 

5857 

5858 More information is available in the C-API section of the manual. 

5859 

5860 Examples 

5861 -------- 

5862 

5863 >>> x = np.dtype('i4') 

5864 >>> x.alignment 

5865 4 

5866 

5867 >>> x = np.dtype(float) 

5868 >>> x.alignment 

5869 8 

5870 

5871 """)) 

5872 

5873add_newdoc('numpy._core.multiarray', 'dtype', ('byteorder', 

5874 """ 

5875 A character indicating the byte-order of this data-type object. 

5876 

5877 One of: 

5878 

5879 === ============== 

5880 '=' native 

5881 '<' little-endian 

5882 '>' big-endian 

5883 '|' not applicable 

5884 === ============== 

5885 

5886 All built-in data-type objects have byteorder either '=' or '|'. 

5887 

5888 Examples 

5889 -------- 

5890 

5891 >>> dt = np.dtype('i2') 

5892 >>> dt.byteorder 

5893 '=' 

5894 >>> # endian is not relevant for 8 bit numbers 

5895 >>> np.dtype('i1').byteorder 

5896 '|' 

5897 >>> # or ASCII strings 

5898 >>> np.dtype('S2').byteorder 

5899 '|' 

5900 >>> # Even if specific code is given, and it is native 

5901 >>> # '=' is the byteorder 

5902 >>> import sys 

5903 >>> sys_is_le = sys.byteorder == 'little' 

5904 >>> native_code = '<' if sys_is_le else '>' 

5905 >>> swapped_code = '>' if sys_is_le else '<' 

5906 >>> dt = np.dtype(native_code + 'i2') 

5907 >>> dt.byteorder 

5908 '=' 

5909 >>> # Swapped code shows up as itself 

5910 >>> dt = np.dtype(swapped_code + 'i2') 

5911 >>> dt.byteorder == swapped_code 

5912 True 

5913 

5914 """)) 

5915 

5916add_newdoc('numpy._core.multiarray', 'dtype', ('char', 

5917 """A unique character code for each of the 21 different built-in types. 

5918 

5919 Examples 

5920 -------- 

5921 

5922 >>> x = np.dtype(float) 

5923 >>> x.char 

5924 'd' 

5925 

5926 """)) 

5927 

5928add_newdoc('numpy._core.multiarray', 'dtype', ('descr', 

5929 """ 

5930 `__array_interface__` description of the data-type. 

5931 

5932 The format is that required by the 'descr' key in the 

5933 `__array_interface__` attribute. 

5934 

5935 Warning: This attribute exists specifically for `__array_interface__`, 

5936 and passing it directly to `numpy.dtype` will not accurately reconstruct 

5937 some dtypes (e.g., scalar and subarray dtypes). 

5938 

5939 Examples 

5940 -------- 

5941 

5942 >>> x = np.dtype(float) 

5943 >>> x.descr 

5944 [('', '<f8')] 

5945 

5946 >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) 

5947 >>> dt.descr 

5948 [('name', '<U16'), ('grades', '<f8', (2,))] 

5949 

5950 """)) 

5951 

5952add_newdoc('numpy._core.multiarray', 'dtype', ('fields', 

5953 """ 

5954 Dictionary of named fields defined for this data type, or ``None``. 

5955 

5956 The dictionary is indexed by keys that are the names of the fields. 

5957 Each entry in the dictionary is a tuple fully describing the field:: 

5958 

5959 (dtype, offset[, title]) 

5960 

5961 Offset is limited to C int, which is signed and usually 32 bits. 

5962 If present, the optional title can be any object (if it is a string 

5963 or unicode then it will also be a key in the fields dictionary, 

5964 otherwise it's meta-data). Notice also that the first two elements 

5965 of the tuple can be passed directly as arguments to the 

5966 ``ndarray.getfield`` and ``ndarray.setfield`` methods. 

5967 

5968 See Also 

5969 -------- 

5970 ndarray.getfield, ndarray.setfield 

5971 

5972 Examples 

5973 -------- 

5974 >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) 

5975 >>> print(dt.fields) 

5976 {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)} 

5977 

5978 """)) 

5979 

5980add_newdoc('numpy._core.multiarray', 'dtype', ('flags', 

5981 """ 

5982 Bit-flags describing how this data type is to be interpreted. 

5983 

5984 Bit-masks are in ``numpy._core.multiarray`` as the constants 

5985 `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`, 

5986 `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation 

5987 of these flags is in C-API documentation; they are largely useful 

5988 for user-defined data-types. 

5989 

5990 The following example demonstrates that operations on this particular 

5991 dtype requires Python C-API. 

5992 

5993 Examples 

5994 -------- 

5995 

5996 >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)]) 

5997 >>> x.flags 

5998 16 

5999 >>> np._core.multiarray.NEEDS_PYAPI 

6000 16 

6001 

6002 """)) 

6003 

6004add_newdoc('numpy._core.multiarray', 'dtype', ('hasobject', 

6005 """ 

6006 Boolean indicating whether this dtype contains any reference-counted 

6007 objects in any fields or sub-dtypes. 

6008 

6009 Recall that what is actually in the ndarray memory representing 

6010 the Python object is the memory address of that object (a pointer). 

6011 Special handling may be required, and this attribute is useful for 

6012 distinguishing data types that may contain arbitrary Python objects 

6013 and data-types that won't. 

6014 

6015 """)) 

6016 

6017add_newdoc('numpy._core.multiarray', 'dtype', ('isbuiltin', 

6018 """ 

6019 Integer indicating how this dtype relates to the built-in dtypes. 

6020 

6021 Read-only. 

6022 

6023 = ======================================================================== 

6024 0 if this is a structured array type, with fields 

6025 1 if this is a dtype compiled into numpy (such as ints, floats etc) 

6026 2 if the dtype is for a user-defined numpy type 

6027 A user-defined type uses the numpy C-API machinery to extend 

6028 numpy to handle a new array type. See 

6029 :ref:`user.user-defined-data-types` in the NumPy manual. 

6030 = ======================================================================== 

6031 

6032 Examples 

6033 -------- 

6034 >>> dt = np.dtype('i2') 

6035 >>> dt.isbuiltin 

6036 1 

6037 >>> dt = np.dtype('f8') 

6038 >>> dt.isbuiltin 

6039 1 

6040 >>> dt = np.dtype([('field1', 'f8')]) 

6041 >>> dt.isbuiltin 

6042 0 

6043 

6044 """)) 

6045 

6046add_newdoc('numpy._core.multiarray', 'dtype', ('isnative', 

6047 """ 

6048 Boolean indicating whether the byte order of this dtype is native 

6049 to the platform. 

6050 

6051 """)) 

6052 

6053add_newdoc('numpy._core.multiarray', 'dtype', ('isalignedstruct', 

6054 """ 

6055 Boolean indicating whether the dtype is a struct which maintains 

6056 field alignment. This flag is sticky, so when combining multiple 

6057 structs together, it is preserved and produces new dtypes which 

6058 are also aligned. 

6059 

6060 """)) 

6061 

6062add_newdoc('numpy._core.multiarray', 'dtype', ('itemsize', 

6063 """ 

6064 The element size of this data-type object. 

6065 

6066 For 18 of the 21 types this number is fixed by the data-type. 

6067 For the flexible data-types, this number can be anything. 

6068 

6069 Examples 

6070 -------- 

6071 

6072 >>> arr = np.array([[1, 2], [3, 4]]) 

6073 >>> arr.dtype 

6074 dtype('int64') 

6075 >>> arr.itemsize 

6076 8 

6077 

6078 >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) 

6079 >>> dt.itemsize 

6080 80 

6081 

6082 """)) 

6083 

6084add_newdoc('numpy._core.multiarray', 'dtype', ('kind', 

6085 """ 

6086 A character code (one of 'biufcmMOSUV') identifying the general kind of data. 

6087 

6088 = ====================== 

6089 b boolean 

6090 i signed integer 

6091 u unsigned integer 

6092 f floating-point 

6093 c complex floating-point 

6094 m timedelta 

6095 M datetime 

6096 O object 

6097 S (byte-)string 

6098 U Unicode 

6099 V void 

6100 = ====================== 

6101 

6102 Examples 

6103 -------- 

6104 

6105 >>> dt = np.dtype('i4') 

6106 >>> dt.kind 

6107 'i' 

6108 >>> dt = np.dtype('f8') 

6109 >>> dt.kind 

6110 'f' 

6111 >>> dt = np.dtype([('field1', 'f8')]) 

6112 >>> dt.kind 

6113 'V' 

6114 

6115 """)) 

6116 

6117add_newdoc('numpy._core.multiarray', 'dtype', ('metadata', 

6118 """ 

6119 Either ``None`` or a readonly dictionary of metadata (mappingproxy). 

6120 

6121 The metadata field can be set using any dictionary at data-type 

6122 creation. NumPy currently has no uniform approach to propagating 

6123 metadata; although some array operations preserve it, there is no 

6124 guarantee that others will. 

6125 

6126 .. warning:: 

6127 

6128 Although used in certain projects, this feature was long undocumented 

6129 and is not well supported. Some aspects of metadata propagation 

6130 are expected to change in the future. 

6131 

6132 Examples 

6133 -------- 

6134 

6135 >>> dt = np.dtype(float, metadata={"key": "value"}) 

6136 >>> dt.metadata["key"] 

6137 'value' 

6138 >>> arr = np.array([1, 2, 3], dtype=dt) 

6139 >>> arr.dtype.metadata 

6140 mappingproxy({'key': 'value'}) 

6141 

6142 Adding arrays with identical datatypes currently preserves the metadata: 

6143 

6144 >>> (arr + arr).dtype.metadata 

6145 mappingproxy({'key': 'value'}) 

6146 

6147 But if the arrays have different dtype metadata, the metadata may be 

6148 dropped: 

6149 

6150 >>> dt2 = np.dtype(float, metadata={"key2": "value2"}) 

6151 >>> arr2 = np.array([3, 2, 1], dtype=dt2) 

6152 >>> (arr + arr2).dtype.metadata is None 

6153 True # The metadata field is cleared so None is returned 

6154 """)) 

6155 

6156add_newdoc('numpy._core.multiarray', 'dtype', ('name', 

6157 """ 

6158 A bit-width name for this data-type. 

6159 

6160 Un-sized flexible data-type objects do not have this attribute. 

6161 

6162 Examples 

6163 -------- 

6164 

6165 >>> x = np.dtype(float) 

6166 >>> x.name 

6167 'float64' 

6168 >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)]) 

6169 >>> x.name 

6170 'void640' 

6171 

6172 """)) 

6173 

6174add_newdoc('numpy._core.multiarray', 'dtype', ('names', 

6175 """ 

6176 Ordered list of field names, or ``None`` if there are no fields. 

6177 

6178 The names are ordered according to increasing byte offset. This can be 

6179 used, for example, to walk through all of the named fields in offset order. 

6180 

6181 Examples 

6182 -------- 

6183 >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) 

6184 >>> dt.names 

6185 ('name', 'grades') 

6186 

6187 """)) 

6188 

6189add_newdoc('numpy._core.multiarray', 'dtype', ('num', 

6190 """ 

6191 A unique number for each of the 21 different built-in types. 

6192 

6193 These are roughly ordered from least-to-most precision. 

6194 

6195 Examples 

6196 -------- 

6197 

6198 >>> dt = np.dtype(str) 

6199 >>> dt.num 

6200 19 

6201 

6202 >>> dt = np.dtype(float) 

6203 >>> dt.num 

6204 12 

6205 

6206 """)) 

6207 

6208add_newdoc('numpy._core.multiarray', 'dtype', ('shape', 

6209 """ 

6210 Shape tuple of the sub-array if this data type describes a sub-array, 

6211 and ``()`` otherwise. 

6212 

6213 Examples 

6214 -------- 

6215 

6216 >>> dt = np.dtype(('i4', 4)) 

6217 >>> dt.shape 

6218 (4,) 

6219 

6220 >>> dt = np.dtype(('i4', (2, 3))) 

6221 >>> dt.shape 

6222 (2, 3) 

6223 

6224 """)) 

6225 

6226add_newdoc('numpy._core.multiarray', 'dtype', ('ndim', 

6227 """ 

6228 Number of dimensions of the sub-array if this data type describes a 

6229 sub-array, and ``0`` otherwise. 

6230 

6231 .. versionadded:: 1.13.0 

6232 

6233 Examples 

6234 -------- 

6235 >>> x = np.dtype(float) 

6236 >>> x.ndim 

6237 0 

6238 

6239 >>> x = np.dtype((float, 8)) 

6240 >>> x.ndim 

6241 1 

6242 

6243 >>> x = np.dtype(('i4', (3, 4))) 

6244 >>> x.ndim 

6245 2 

6246 

6247 """)) 

6248 

6249add_newdoc('numpy._core.multiarray', 'dtype', ('str', 

6250 """The array-protocol typestring of this data-type object.""")) 

6251 

6252add_newdoc('numpy._core.multiarray', 'dtype', ('subdtype', 

6253 """ 

6254 Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and 

6255 None otherwise. 

6256 

6257 The *shape* is the fixed shape of the sub-array described by this 

6258 data type, and *item_dtype* the data type of the array. 

6259 

6260 If a field whose dtype object has this attribute is retrieved, 

6261 then the extra dimensions implied by *shape* are tacked on to 

6262 the end of the retrieved array. 

6263 

6264 See Also 

6265 -------- 

6266 dtype.base 

6267 

6268 Examples 

6269 -------- 

6270 >>> x = numpy.dtype('8f') 

6271 >>> x.subdtype 

6272 (dtype('float32'), (8,)) 

6273 

6274 >>> x = numpy.dtype('i2') 

6275 >>> x.subdtype 

6276 >>> 

6277 

6278 """)) 

6279 

6280add_newdoc('numpy._core.multiarray', 'dtype', ('base', 

6281 """ 

6282 Returns dtype for the base element of the subarrays, 

6283 regardless of their dimension or shape. 

6284 

6285 See Also 

6286 -------- 

6287 dtype.subdtype 

6288 

6289 Examples 

6290 -------- 

6291 >>> x = numpy.dtype('8f') 

6292 >>> x.base 

6293 dtype('float32') 

6294 

6295 >>> x = numpy.dtype('i2') 

6296 >>> x.base 

6297 dtype('int16') 

6298 

6299 """)) 

6300 

6301add_newdoc('numpy._core.multiarray', 'dtype', ('type', 

6302 """The type object used to instantiate a scalar of this data-type.""")) 

6303 

6304############################################################################## 

6305# 

6306# dtype methods 

6307# 

6308############################################################################## 

6309 

6310add_newdoc('numpy._core.multiarray', 'dtype', ('newbyteorder', 

6311 """ 

6312 newbyteorder(new_order='S', /) 

6313 

6314 Return a new dtype with a different byte order. 

6315 

6316 Changes are also made in all fields and sub-arrays of the data type. 

6317 

6318 Parameters 

6319 ---------- 

6320 new_order : string, optional 

6321 Byte order to force; a value from the byte order specifications 

6322 below. The default value ('S') results in swapping the current 

6323 byte order. `new_order` codes can be any of: 

6324 

6325 * 'S' - swap dtype from current to opposite endian 

6326 * {'<', 'little'} - little endian 

6327 * {'>', 'big'} - big endian 

6328 * {'=', 'native'} - native order 

6329 * {'|', 'I'} - ignore (no change to byte order) 

6330 

6331 Returns 

6332 ------- 

6333 new_dtype : dtype 

6334 New dtype object with the given change to the byte order. 

6335 

6336 Notes 

6337 ----- 

6338 Changes are also made in all fields and sub-arrays of the data type. 

6339 

6340 Examples 

6341 -------- 

6342 >>> import sys 

6343 >>> sys_is_le = sys.byteorder == 'little' 

6344 >>> native_code = '<' if sys_is_le else '>' 

6345 >>> swapped_code = '>' if sys_is_le else '<' 

6346 >>> native_dt = np.dtype(native_code+'i2') 

6347 >>> swapped_dt = np.dtype(swapped_code+'i2') 

6348 >>> native_dt.newbyteorder('S') == swapped_dt 

6349 True 

6350 >>> native_dt.newbyteorder() == swapped_dt 

6351 True 

6352 >>> native_dt == swapped_dt.newbyteorder('S') 

6353 True 

6354 >>> native_dt == swapped_dt.newbyteorder('=') 

6355 True 

6356 >>> native_dt == swapped_dt.newbyteorder('N') 

6357 True 

6358 >>> native_dt == native_dt.newbyteorder('|') 

6359 True 

6360 >>> np.dtype('<i2') == native_dt.newbyteorder('<') 

6361 True 

6362 >>> np.dtype('<i2') == native_dt.newbyteorder('L') 

6363 True 

6364 >>> np.dtype('>i2') == native_dt.newbyteorder('>') 

6365 True 

6366 >>> np.dtype('>i2') == native_dt.newbyteorder('B') 

6367 True 

6368 

6369 """)) 

6370 

6371add_newdoc('numpy._core.multiarray', 'dtype', ('__class_getitem__', 

6372 """ 

6373 __class_getitem__(item, /) 

6374 

6375 Return a parametrized wrapper around the `~numpy.dtype` type. 

6376 

6377 .. versionadded:: 1.22 

6378 

6379 Returns 

6380 ------- 

6381 alias : types.GenericAlias 

6382 A parametrized `~numpy.dtype` type. 

6383 

6384 Examples 

6385 -------- 

6386 >>> import numpy as np 

6387 

6388 >>> np.dtype[np.int64] 

6389 numpy.dtype[numpy.int64] 

6390 

6391 See Also 

6392 -------- 

6393 :pep:`585` : Type hinting generics in standard collections. 

6394 

6395 """)) 

6396 

6397add_newdoc('numpy._core.multiarray', 'dtype', ('__ge__', 

6398 """ 

6399 __ge__(value, /) 

6400 

6401 Return ``self >= value``. 

6402 

6403 Equivalent to ``np.can_cast(value, self, casting="safe")``. 

6404 

6405 See Also 

6406 -------- 

6407 can_cast : Returns True if cast between data types can occur according to 

6408 the casting rule. 

6409 

6410 """)) 

6411 

6412add_newdoc('numpy._core.multiarray', 'dtype', ('__le__', 

6413 """ 

6414 __le__(value, /) 

6415 

6416 Return ``self <= value``. 

6417 

6418 Equivalent to ``np.can_cast(self, value, casting="safe")``. 

6419 

6420 See Also 

6421 -------- 

6422 can_cast : Returns True if cast between data types can occur according to 

6423 the casting rule. 

6424 

6425 """)) 

6426 

6427add_newdoc('numpy._core.multiarray', 'dtype', ('__gt__', 

6428 """ 

6429 __ge__(value, /) 

6430 

6431 Return ``self > value``. 

6432 

6433 Equivalent to 

6434 ``self != value and np.can_cast(value, self, casting="safe")``. 

6435 

6436 See Also 

6437 -------- 

6438 can_cast : Returns True if cast between data types can occur according to 

6439 the casting rule. 

6440 

6441 """)) 

6442 

6443add_newdoc('numpy._core.multiarray', 'dtype', ('__lt__', 

6444 """ 

6445 __lt__(value, /) 

6446 

6447 Return ``self < value``. 

6448 

6449 Equivalent to 

6450 ``self != value and np.can_cast(self, value, casting="safe")``. 

6451 

6452 See Also 

6453 -------- 

6454 can_cast : Returns True if cast between data types can occur according to 

6455 the casting rule. 

6456 

6457 """)) 

6458 

6459############################################################################## 

6460# 

6461# Datetime-related Methods 

6462# 

6463############################################################################## 

6464 

6465add_newdoc('numpy._core.multiarray', 'busdaycalendar', 

6466 """ 

6467 busdaycalendar(weekmask='1111100', holidays=None) 

6468 

6469 A business day calendar object that efficiently stores information 

6470 defining valid days for the busday family of functions. 

6471 

6472 The default valid days are Monday through Friday ("business days"). 

6473 A busdaycalendar object can be specified with any set of weekly 

6474 valid days, plus an optional "holiday" dates that always will be invalid. 

6475 

6476 Once a busdaycalendar object is created, the weekmask and holidays 

6477 cannot be modified. 

6478 

6479 .. versionadded:: 1.7.0 

6480 

6481 Parameters 

6482 ---------- 

6483 weekmask : str or array_like of bool, optional 

6484 A seven-element array indicating which of Monday through Sunday are 

6485 valid days. May be specified as a length-seven list or array, like 

6486 [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string 

6487 like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for 

6488 weekdays, optionally separated by white space. Valid abbreviations 

6489 are: Mon Tue Wed Thu Fri Sat Sun 

6490 holidays : array_like of datetime64[D], optional 

6491 An array of dates to consider as invalid dates, no matter which 

6492 weekday they fall upon. Holiday dates may be specified in any 

6493 order, and NaT (not-a-time) dates are ignored. This list is 

6494 saved in a normalized form that is suited for fast calculations 

6495 of valid days. 

6496 

6497 Returns 

6498 ------- 

6499 out : busdaycalendar 

6500 A business day calendar object containing the specified 

6501 weekmask and holidays values. 

6502 

6503 See Also 

6504 -------- 

6505 is_busday : Returns a boolean array indicating valid days. 

6506 busday_offset : Applies an offset counted in valid days. 

6507 busday_count : Counts how many valid days are in a half-open date range. 

6508 

6509 Attributes 

6510 ---------- 

6511 weekmask : (copy) seven-element array of bool 

6512 holidays : (copy) sorted array of datetime64[D] 

6513 

6514 Notes 

6515 ----- 

6516 Once a busdaycalendar object is created, you cannot modify the 

6517 weekmask or holidays. The attributes return copies of internal data. 

6518 

6519 Examples 

6520 -------- 

6521 >>> # Some important days in July 

6522 ... bdd = np.busdaycalendar( 

6523 ... holidays=['2011-07-01', '2011-07-04', '2011-07-17']) 

6524 >>> # Default is Monday to Friday weekdays 

6525 ... bdd.weekmask 

6526 array([ True, True, True, True, True, False, False]) 

6527 >>> # Any holidays already on the weekend are removed 

6528 ... bdd.holidays 

6529 array(['2011-07-01', '2011-07-04'], dtype='datetime64[D]') 

6530 """) 

6531 

6532add_newdoc('numpy._core.multiarray', 'busdaycalendar', ('weekmask', 

6533 """A copy of the seven-element boolean mask indicating valid days.""")) 

6534 

6535add_newdoc('numpy._core.multiarray', 'busdaycalendar', ('holidays', 

6536 """A copy of the holiday array indicating additional invalid days.""")) 

6537 

6538add_newdoc('numpy._core.multiarray', 'normalize_axis_index', 

6539 """ 

6540 normalize_axis_index(axis, ndim, msg_prefix=None) 

6541 

6542 Normalizes an axis index, `axis`, such that is a valid positive index into 

6543 the shape of array with `ndim` dimensions. Raises an AxisError with an 

6544 appropriate message if this is not possible. 

6545 

6546 Used internally by all axis-checking logic. 

6547 

6548 .. versionadded:: 1.13.0 

6549 

6550 Parameters 

6551 ---------- 

6552 axis : int 

6553 The un-normalized index of the axis. Can be negative 

6554 ndim : int 

6555 The number of dimensions of the array that `axis` should be normalized 

6556 against 

6557 msg_prefix : str 

6558 A prefix to put before the message, typically the name of the argument 

6559 

6560 Returns 

6561 ------- 

6562 normalized_axis : int 

6563 The normalized axis index, such that `0 <= normalized_axis < ndim` 

6564 

6565 Raises 

6566 ------ 

6567 AxisError 

6568 If the axis index is invalid, when `-ndim <= axis < ndim` is false. 

6569 

6570 Examples 

6571 -------- 

6572 >>> from numpy.lib.array_utils import normalize_axis_index 

6573 >>> normalize_axis_index(0, ndim=3) 

6574 0 

6575 >>> normalize_axis_index(1, ndim=3) 

6576 1 

6577 >>> normalize_axis_index(-1, ndim=3) 

6578 2 

6579 

6580 >>> normalize_axis_index(3, ndim=3) 

6581 Traceback (most recent call last): 

6582 ... 

6583 numpy.exceptions.AxisError: axis 3 is out of bounds for array ... 

6584 >>> normalize_axis_index(-4, ndim=3, msg_prefix='axes_arg') 

6585 Traceback (most recent call last): 

6586 ... 

6587 numpy.exceptions.AxisError: axes_arg: axis -4 is out of bounds ... 

6588 """) 

6589 

6590add_newdoc('numpy._core.multiarray', 'datetime_data', 

6591 """ 

6592 datetime_data(dtype, /) 

6593 

6594 Get information about the step size of a date or time type. 

6595 

6596 The returned tuple can be passed as the second argument of `numpy.datetime64` and 

6597 `numpy.timedelta64`. 

6598 

6599 Parameters 

6600 ---------- 

6601 dtype : dtype 

6602 The dtype object, which must be a `datetime64` or `timedelta64` type. 

6603 

6604 Returns 

6605 ------- 

6606 unit : str 

6607 The :ref:`datetime unit <arrays.dtypes.dateunits>` on which this dtype 

6608 is based. 

6609 count : int 

6610 The number of base units in a step. 

6611 

6612 Examples 

6613 -------- 

6614 >>> dt_25s = np.dtype('timedelta64[25s]') 

6615 >>> np.datetime_data(dt_25s) 

6616 ('s', 25) 

6617 >>> np.array(10, dt_25s).astype('timedelta64[s]') 

6618 array(250, dtype='timedelta64[s]') 

6619 

6620 The result can be used to construct a datetime that uses the same units 

6621 as a timedelta 

6622 

6623 >>> np.datetime64('2010', np.datetime_data(dt_25s)) 

6624 numpy.datetime64('2010-01-01T00:00:00','25s') 

6625 """) 

6626 

6627 

6628############################################################################## 

6629# 

6630# Documentation for `generic` attributes and methods 

6631# 

6632############################################################################## 

6633 

6634add_newdoc('numpy._core.numerictypes', 'generic', 

6635 """ 

6636 Base class for numpy scalar types. 

6637 

6638 Class from which most (all?) numpy scalar types are derived. For 

6639 consistency, exposes the same API as `ndarray`, despite many 

6640 consequent attributes being either "get-only," or completely irrelevant. 

6641 This is the class from which it is strongly suggested users should derive 

6642 custom scalar types. 

6643 

6644 """) 

6645 

6646# Attributes 

6647 

6648def refer_to_array_attribute(attr, method=True): 

6649 docstring = """ 

6650 Scalar {} identical to the corresponding array attribute. 

6651 

6652 Please see `ndarray.{}`. 

6653 """ 

6654 

6655 return attr, docstring.format("method" if method else "attribute", attr) 

6656 

6657 

6658add_newdoc('numpy._core.numerictypes', 'generic', 

6659 refer_to_array_attribute('T', method=False)) 

6660 

6661add_newdoc('numpy._core.numerictypes', 'generic', 

6662 refer_to_array_attribute('base', method=False)) 

6663 

6664add_newdoc('numpy._core.numerictypes', 'generic', ('data', 

6665 """Pointer to start of data.""")) 

6666 

6667add_newdoc('numpy._core.numerictypes', 'generic', ('dtype', 

6668 """Get array data-descriptor.""")) 

6669 

6670add_newdoc('numpy._core.numerictypes', 'generic', ('flags', 

6671 """The integer value of flags.""")) 

6672 

6673add_newdoc('numpy._core.numerictypes', 'generic', ('flat', 

6674 """A 1-D view of the scalar.""")) 

6675 

6676add_newdoc('numpy._core.numerictypes', 'generic', ('imag', 

6677 """The imaginary part of the scalar.""")) 

6678 

6679add_newdoc('numpy._core.numerictypes', 'generic', ('itemsize', 

6680 """The length of one element in bytes.""")) 

6681 

6682add_newdoc('numpy._core.numerictypes', 'generic', ('ndim', 

6683 """The number of array dimensions.""")) 

6684 

6685add_newdoc('numpy._core.numerictypes', 'generic', ('real', 

6686 """The real part of the scalar.""")) 

6687 

6688add_newdoc('numpy._core.numerictypes', 'generic', ('shape', 

6689 """Tuple of array dimensions.""")) 

6690 

6691add_newdoc('numpy._core.numerictypes', 'generic', ('size', 

6692 """The number of elements in the gentype.""")) 

6693 

6694add_newdoc('numpy._core.numerictypes', 'generic', ('strides', 

6695 """Tuple of bytes steps in each dimension.""")) 

6696 

6697# Methods 

6698 

6699add_newdoc('numpy._core.numerictypes', 'generic', 

6700 refer_to_array_attribute('all')) 

6701 

6702add_newdoc('numpy._core.numerictypes', 'generic', 

6703 refer_to_array_attribute('any')) 

6704 

6705add_newdoc('numpy._core.numerictypes', 'generic', 

6706 refer_to_array_attribute('argmax')) 

6707 

6708add_newdoc('numpy._core.numerictypes', 'generic', 

6709 refer_to_array_attribute('argmin')) 

6710 

6711add_newdoc('numpy._core.numerictypes', 'generic', 

6712 refer_to_array_attribute('argsort')) 

6713 

6714add_newdoc('numpy._core.numerictypes', 'generic', 

6715 refer_to_array_attribute('astype')) 

6716 

6717add_newdoc('numpy._core.numerictypes', 'generic', 

6718 refer_to_array_attribute('byteswap')) 

6719 

6720add_newdoc('numpy._core.numerictypes', 'generic', 

6721 refer_to_array_attribute('choose')) 

6722 

6723add_newdoc('numpy._core.numerictypes', 'generic', 

6724 refer_to_array_attribute('clip')) 

6725 

6726add_newdoc('numpy._core.numerictypes', 'generic', 

6727 refer_to_array_attribute('compress')) 

6728 

6729add_newdoc('numpy._core.numerictypes', 'generic', 

6730 refer_to_array_attribute('conjugate')) 

6731 

6732add_newdoc('numpy._core.numerictypes', 'generic', 

6733 refer_to_array_attribute('copy')) 

6734 

6735add_newdoc('numpy._core.numerictypes', 'generic', 

6736 refer_to_array_attribute('cumprod')) 

6737 

6738add_newdoc('numpy._core.numerictypes', 'generic', 

6739 refer_to_array_attribute('cumsum')) 

6740 

6741add_newdoc('numpy._core.numerictypes', 'generic', 

6742 refer_to_array_attribute('diagonal')) 

6743 

6744add_newdoc('numpy._core.numerictypes', 'generic', 

6745 refer_to_array_attribute('dump')) 

6746 

6747add_newdoc('numpy._core.numerictypes', 'generic', 

6748 refer_to_array_attribute('dumps')) 

6749 

6750add_newdoc('numpy._core.numerictypes', 'generic', 

6751 refer_to_array_attribute('fill')) 

6752 

6753add_newdoc('numpy._core.numerictypes', 'generic', 

6754 refer_to_array_attribute('flatten')) 

6755 

6756add_newdoc('numpy._core.numerictypes', 'generic', 

6757 refer_to_array_attribute('getfield')) 

6758 

6759add_newdoc('numpy._core.numerictypes', 'generic', 

6760 refer_to_array_attribute('item')) 

6761 

6762add_newdoc('numpy._core.numerictypes', 'generic', 

6763 refer_to_array_attribute('max')) 

6764 

6765add_newdoc('numpy._core.numerictypes', 'generic', 

6766 refer_to_array_attribute('mean')) 

6767 

6768add_newdoc('numpy._core.numerictypes', 'generic', 

6769 refer_to_array_attribute('min')) 

6770 

6771add_newdoc('numpy._core.numerictypes', 'generic', 

6772 refer_to_array_attribute('nonzero')) 

6773 

6774add_newdoc('numpy._core.numerictypes', 'generic', 

6775 refer_to_array_attribute('prod')) 

6776 

6777add_newdoc('numpy._core.numerictypes', 'generic', 

6778 refer_to_array_attribute('put')) 

6779 

6780add_newdoc('numpy._core.numerictypes', 'generic', 

6781 refer_to_array_attribute('ravel')) 

6782 

6783add_newdoc('numpy._core.numerictypes', 'generic', 

6784 refer_to_array_attribute('repeat')) 

6785 

6786add_newdoc('numpy._core.numerictypes', 'generic', 

6787 refer_to_array_attribute('reshape')) 

6788 

6789add_newdoc('numpy._core.numerictypes', 'generic', 

6790 refer_to_array_attribute('resize')) 

6791 

6792add_newdoc('numpy._core.numerictypes', 'generic', 

6793 refer_to_array_attribute('round')) 

6794 

6795add_newdoc('numpy._core.numerictypes', 'generic', 

6796 refer_to_array_attribute('searchsorted')) 

6797 

6798add_newdoc('numpy._core.numerictypes', 'generic', 

6799 refer_to_array_attribute('setfield')) 

6800 

6801add_newdoc('numpy._core.numerictypes', 'generic', 

6802 refer_to_array_attribute('setflags')) 

6803 

6804add_newdoc('numpy._core.numerictypes', 'generic', 

6805 refer_to_array_attribute('sort')) 

6806 

6807add_newdoc('numpy._core.numerictypes', 'generic', 

6808 refer_to_array_attribute('squeeze')) 

6809 

6810add_newdoc('numpy._core.numerictypes', 'generic', 

6811 refer_to_array_attribute('std')) 

6812 

6813add_newdoc('numpy._core.numerictypes', 'generic', 

6814 refer_to_array_attribute('sum')) 

6815 

6816add_newdoc('numpy._core.numerictypes', 'generic', 

6817 refer_to_array_attribute('swapaxes')) 

6818 

6819add_newdoc('numpy._core.numerictypes', 'generic', 

6820 refer_to_array_attribute('take')) 

6821 

6822add_newdoc('numpy._core.numerictypes', 'generic', 

6823 refer_to_array_attribute('tofile')) 

6824 

6825add_newdoc('numpy._core.numerictypes', 'generic', 

6826 refer_to_array_attribute('tolist')) 

6827 

6828add_newdoc('numpy._core.numerictypes', 'generic', 

6829 refer_to_array_attribute('tostring')) 

6830 

6831add_newdoc('numpy._core.numerictypes', 'generic', 

6832 refer_to_array_attribute('trace')) 

6833 

6834add_newdoc('numpy._core.numerictypes', 'generic', 

6835 refer_to_array_attribute('transpose')) 

6836 

6837add_newdoc('numpy._core.numerictypes', 'generic', 

6838 refer_to_array_attribute('var')) 

6839 

6840add_newdoc('numpy._core.numerictypes', 'generic', 

6841 refer_to_array_attribute('view')) 

6842 

6843add_newdoc('numpy._core.numerictypes', 'number', ('__class_getitem__', 

6844 """ 

6845 __class_getitem__(item, /) 

6846 

6847 Return a parametrized wrapper around the `~numpy.number` type. 

6848 

6849 .. versionadded:: 1.22 

6850 

6851 Returns 

6852 ------- 

6853 alias : types.GenericAlias 

6854 A parametrized `~numpy.number` type. 

6855 

6856 Examples 

6857 -------- 

6858 >>> from typing import Any 

6859 >>> import numpy as np 

6860 

6861 >>> np.signedinteger[Any] 

6862 numpy.signedinteger[typing.Any] 

6863 

6864 See Also 

6865 -------- 

6866 :pep:`585` : Type hinting generics in standard collections. 

6867 

6868 """)) 

6869 

6870############################################################################## 

6871# 

6872# Documentation for scalar type abstract base classes in type hierarchy 

6873# 

6874############################################################################## 

6875 

6876 

6877add_newdoc('numpy._core.numerictypes', 'number', 

6878 """ 

6879 Abstract base class of all numeric scalar types. 

6880 

6881 """) 

6882 

6883add_newdoc('numpy._core.numerictypes', 'integer', 

6884 """ 

6885 Abstract base class of all integer scalar types. 

6886 

6887 """) 

6888 

6889add_newdoc('numpy._core.numerictypes', 'signedinteger', 

6890 """ 

6891 Abstract base class of all signed integer scalar types. 

6892 

6893 """) 

6894 

6895add_newdoc('numpy._core.numerictypes', 'unsignedinteger', 

6896 """ 

6897 Abstract base class of all unsigned integer scalar types. 

6898 

6899 """) 

6900 

6901add_newdoc('numpy._core.numerictypes', 'inexact', 

6902 """ 

6903 Abstract base class of all numeric scalar types with a (potentially) 

6904 inexact representation of the values in its range, such as 

6905 floating-point numbers. 

6906 

6907 """) 

6908 

6909add_newdoc('numpy._core.numerictypes', 'floating', 

6910 """ 

6911 Abstract base class of all floating-point scalar types. 

6912 

6913 """) 

6914 

6915add_newdoc('numpy._core.numerictypes', 'complexfloating', 

6916 """ 

6917 Abstract base class of all complex number scalar types that are made up of 

6918 floating-point numbers. 

6919 

6920 """) 

6921 

6922add_newdoc('numpy._core.numerictypes', 'flexible', 

6923 """ 

6924 Abstract base class of all scalar types without predefined length. 

6925 The actual size of these types depends on the specific `numpy.dtype` 

6926 instantiation. 

6927 

6928 """) 

6929 

6930add_newdoc('numpy._core.numerictypes', 'character', 

6931 """ 

6932 Abstract base class of all character string scalar types. 

6933 

6934 """) 

6935 

6936add_newdoc('numpy._core.multiarray', 'StringDType', 

6937 """ 

6938 StringDType(*, na_object=np._NoValue, coerce=True) 

6939 

6940 Create a StringDType instance. 

6941 

6942 StringDType can be used to store UTF-8 encoded variable-width strings in 

6943 a NumPy array. 

6944 

6945 Parameters 

6946 ---------- 

6947 na_object : object, optional 

6948 Object used to represent missing data. If unset, the array will not 

6949 use a missing data sentinel. 

6950 coerce : bool, optional 

6951 Whether or not items in an array-like passed to an array creation 

6952 function that are neither a str or str subtype should be coerced to 

6953 str. Defaults to True. If set to False, creating a StringDType 

6954 array from an array-like containing entries that are not already 

6955 strings will raise an error. 

6956 

6957 Examples 

6958 -------- 

6959 

6960 >>> from numpy.dtypes import StringDType 

6961 >>> np.array(["hello", "world"], dtype=StringDType()) 

6962 array(["hello", "world"], dtype=StringDType()) 

6963 

6964 >>> arr = np.array(["hello", None, "world"], 

6965 dtype=StringDType(na_object=None)) 

6966 >>> arr 

6967 array(["hello", None, "world", dtype=StringDType(na_object=None)) 

6968 >>> arr[1] is None 

6969 True 

6970 

6971 >>> arr = np.array(["hello", np.nan, "world"], 

6972 dtype=StringDType(na_object=np.nan)) 

6973 >>> np.isnan(arr) 

6974 array([False, True, False]) 

6975 

6976 >>> np.array([1.2, object(), "hello world"], 

6977 dtype=StringDType(coerce=True)) 

6978 ValueError: StringDType only allows string data when string coercion 

6979 is disabled. 

6980 

6981 >>> np.array(["hello", "world"], dtype=StringDType(coerce=True)) 

6982 array(["hello", "world"], dtype=StringDType(coerce=True)) 

6983 """)