1"""

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

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

4 requiring a re-compile.

5

6 NOTE: 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, core/defmatrix.py up-to-date.

9

10"""

11

12 from numpy.core.function_base import add_newdoc

13 from numpy.core.overrides import array_function_like_doc

14

15###############################################################################

16#

17# flatiter

18#

19# flatiter needs a toplevel description

20#

21###############################################################################

22

23 add_newdoc('numpy.core', 'flatiter',

24 """

25 Flat iterator object to iterate over arrays.

26

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

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

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

30

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

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

33 basic slicing or advanced indexing.

34

35 See Also

36 --------

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

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

39

40 Notes

41 -----

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

43 by calling the `flatiter` constructor.

44

45 Examples

46 --------

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

48 >>> fl = x.flat

49 >>> type(fl)

50 <class 'numpy.flatiter'>

51 >>> for item in fl:

52 ... print(item)

53 ...

54 0

55 1

56 2

57 3

58 4

59 5

60

61 >>> fl[2:4]

62 array([2, 3])

63

64 """)

65

66# flatiter attributes

67

68 add_newdoc('numpy.core', 'flatiter', ('base',

69 """

70 A reference to the array that is iterated over.

71

72 Examples

73 --------

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

75 >>> fl = x.flat

76 >>> fl.base is x

77 True

78

79 """))

80

81

82

83 add_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

101

102 add_newdoc('numpy.core', 'flatiter', ('index',

103 """

104 Current flat index into the array.

105

106 Examples

107 --------

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

109 >>> fl = x.flat

110 >>> fl.index

111 0

112 >>> next(fl)

113 0

114 >>> fl.index

115 1

116

117 """))

118

119# flatiter functions

120

121 add_newdoc('numpy.core', 'flatiter', ('__array__',

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

123

124 """))

125

126

127 add_newdoc('numpy.core', 'flatiter', ('copy',

128 """

129 copy()

130

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

132

133 Examples

134 --------

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

136 >>> x

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

138 [3, 4, 5]])

139 >>> fl = x.flat

140 >>> fl.copy()

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

142

143 """))

144

145

146###############################################################################

147#

148# nditer

149#

150###############################################################################

151

152 add_newdoc('numpy.core', 'nditer',

153 """

154 nditer(op, flags=None, op_flags=None, op_dtypes=None, order='K', 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 `__exit__` function is called but not before:

393

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

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

396 ... [['writeonly', 'updateifcopy']],

397 ... casting='unsafe',

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

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

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

401 ... # a still unchanged here

402 >>> a, x

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

404

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

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

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

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

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

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

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

412 one will affect the other.

413

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

415

416 """)

417

418# nditer methods

419

420 add_newdoc('numpy.core', 'nditer', ('copy',

421 """

422 copy()

423

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

425

426 Examples

427 --------

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

429 >>> y = x + 1

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

431 >>> next(it)

432 (array(0), array(1))

433 >>> it2 = it.copy()

434 >>> next(it2)

435 (array(1), array(2))

436

437 """))

438

439 add_newdoc('numpy.core', 'nditer', ('operands',

440 """

441 operands[`Slice`]

442

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

444 """))

445

446 add_newdoc('numpy.core', 'nditer', ('debug_print',

447 """

448 debug_print()

449

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

451

452 """))

453

454 add_newdoc('numpy.core', 'nditer', ('enable_external_loop',

455 """

456 enable_external_loop()

457

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

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

460 was specified.

461

462 """))

463

464 add_newdoc('numpy.core', 'nditer', ('iternext',

465 """

466 iternext()

467

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

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

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

471

472 Returns

473 -------

474 iternext : bool

475 Whether or not there are iterations left.

476

477 """))

478

479 add_newdoc('numpy.core', 'nditer', ('remove_axis',

480 """

481 remove_axis(i, /)

482

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

484 be enabled.

485

486 """))

487

488 add_newdoc('numpy.core', 'nditer', ('remove_multi_index',

489 """

490 remove_multi_index()

491

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

493 the internal iteration structure to be optimized further.

494

495 """))

496

497 add_newdoc('numpy.core', 'nditer', ('reset',

498 """

499 reset()

500

501 Reset the iterator to its initial state.

502

503 """))

504

505 add_newdoc('numpy.core', 'nested_iters',

506 """

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

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

509

510 Create nditers for use in nested loops

511

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

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

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

515 the subsequent iterators to point at its new element.

516

517 Parameters

518 ----------

519 op : ndarray or sequence of array_like

520 The array(s) to iterate over.

521

522 axes : list of list of int

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

524

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

526 See `nditer` parameters of the same name

527

528 Returns

529 -------

530 iters : tuple of nditer

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

532

533 See Also

534 --------

535 nditer

536

537 Examples

538 --------

539

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

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

542 the first iter's axes as [1]

543

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

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

546 >>> for x in i:

547 ... print(i.multi_index)

548 ... for y in j:

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

550 (0,)

551 (0, 0) 0

552 (0, 1) 1

553 (1, 0) 6

554 (1, 1) 7

555 (1,)

556 (0, 0) 2

557 (0, 1) 3

558 (1, 0) 8

559 (1, 1) 9

560 (2,)

561 (0, 0) 4

562 (0, 1) 5

563 (1, 0) 10

564 (1, 1) 11

565

566 """)

567

568 add_newdoc('numpy.core', 'nditer', ('close',

569 """

570 close()

571

572 Resolve all writeback semantics in writeable operands.

573

574 .. versionadded:: 1.15.0

575

576 See Also

577 --------

578

579 :ref:`nditer-context-manager`

580

581 """))

582

583

584###############################################################################

585#

586# broadcast

587#

588###############################################################################

589

590 add_newdoc('numpy.core', 'broadcast',

591 """

592 Produce an object that mimics broadcasting.

593

594 Parameters

595 ----------

596 in1, in2, ... : array_like

597 Input parameters.

598

599 Returns

600 -------

601 b : broadcast object

602 Broadcast the input parameters against one another, and

603 return an object that encapsulates the result.

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

605 may be used as an iterator.

606

607 See Also

608 --------

609 broadcast_arrays

610 broadcast_to

611 broadcast_shapes

612

613 Examples

614 --------

615

616 Manually adding two vectors, using broadcasting:

617

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

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

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

621

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

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

624 >>> out

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

626 [6., 7., 8.],

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

628

629 Compare against built-in broadcasting:

630

631 >>> x + y

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

633 [6, 7, 8],

634 [7, 8, 9]])

635

636 """)

637

638# attributes

639

640 add_newdoc('numpy.core', 'broadcast', ('index',

641 """

642 current index in broadcasted result

643

644 Examples

645 --------

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

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

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

649 >>> b.index

650 0

651 >>> next(b), next(b), next(b)

652 ((1, 4), (1, 5), (1, 6))

653 >>> b.index

654 3

655

656 """))

657

658 add_newdoc('numpy.core', 'broadcast', ('iters',

659 """

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

661

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

663 of ``self``.

664

665 See Also

666 --------

667 numpy.flatiter

668

669 Examples

670 --------

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

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

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

674 >>> row, col = b.iters

675 >>> next(row), next(col)

676 (1, 4)

677

678 """))

679

680 add_newdoc('numpy.core', 'broadcast', ('ndim',

681 """

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

683

684 .. versionadded:: 1.12.0

685

686 Examples

687 --------

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

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

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

691 >>> b.ndim

692 2

693

694 """))

695

696 add_newdoc('numpy.core', 'broadcast', ('nd',

697 """

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

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

700

701 Examples

702 --------

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

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

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

706 >>> b.nd

707 2

708

709 """))

710

711 add_newdoc('numpy.core', 'broadcast', ('numiter',

712 """

713 Number of iterators possessed by the broadcasted result.

714

715 Examples

716 --------

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

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

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

720 >>> b.numiter

721 2

722

723 """))

724

725 add_newdoc('numpy.core', 'broadcast', ('shape',

726 """

727 Shape of broadcasted result.

728

729 Examples

730 --------

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

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

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

734 >>> b.shape

735 (3, 3)

736

737 """))

738

739 add_newdoc('numpy.core', 'broadcast', ('size',

740 """

741 Total size of broadcasted result.

742

743 Examples

744 --------

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

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

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

748 >>> b.size

749 9

750

751 """))

752

753 add_newdoc('numpy.core', 'broadcast', ('reset',

754 """

755 reset()

756

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

758

759 Parameters

760 ----------

761 None

762

763 Returns

764 -------

765 None

766

767 Examples

768 --------

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

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

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

772 >>> b.index

773 0

774 >>> next(b), next(b), next(b)

775 ((1, 4), (2, 4), (3, 4))

776 >>> b.index

777 3

778 >>> b.reset()

779 >>> b.index

780 0

781

782 """))

783

784###############################################################################

785#

786# numpy functions

787#

788###############################################################################

789

790 add_newdoc('numpy.core.multiarray', 'array',

791 """

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

793 like=None)

794

795 Create an array.

796

797 Parameters

798 ----------

799 object : array_like

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

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

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

803 returned.

804 dtype : data-type, optional

805 The desired data-type for the array. If not given, then the type will

806 be determined as the minimum type required to hold the objects in the

807 sequence.

808 copy : bool, optional

809 If true (default), then the object is copied. Otherwise, a copy will

810 only be made if __array__ returns a copy, if obj is a nested sequence,

811 or if a copy is needed to satisfy any of the other requirements

812 (`dtype`, `order`, etc.).

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

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

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

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

817 If object is an array the following holds.

818

819 ===== ========= ===================================================

820 order no copy copy=True

821 ===== ========= ===================================================

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

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

824 'C' C order C order

825 'F' F order F order

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

827

828 When ``copy=False`` and a copy is made for other reasons, the result is

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

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

831 subok : bool, optional

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

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

834 ndmin : int, optional

835 Specifies the minimum number of dimensions that the resulting

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

837 needed to meet this requirement.

838 ${ARRAY_FUNCTION_LIKE}

839

840 .. versionadded:: 1.20.0

841

842 Returns

843 -------

844 out : ndarray

845 An array object satisfying the specified requirements.

846

847 See Also

848 --------

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

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

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

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

853 empty : Return a new uninitialized array.

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

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

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

857

858

859 Notes

860 -----

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

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

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

864

865 Examples

866 --------

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

868 array([1, 2, 3])

869

870 Upcasting:

871

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

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

874

875 More than one dimension:

876

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

878 array([[1, 2],

879 [3, 4]])

880

881 Minimum dimensions 2:

882

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

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

885

886 Type provided:

887

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

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

890

891 Data-type consisting of more than one element:

892

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

894 >>> x['a']

895 array([1, 3])

896

897 Creating an array from sub-classes:

898

899 >>> np.array(np.mat('1 2; 3 4'))

900 array([[1, 2],

901 [3, 4]])

902

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

904 matrix([[1, 2],

905 [3, 4]])

906

907 """.replace(

908 "${ARRAY_FUNCTION_LIKE}",

909 array_function_like_doc,

910 ))

911

912 add_newdoc('numpy.core.multiarray', 'asarray',

913 """

914 asarray(a, dtype=None, order=None, *, like=None)

915

916 Convert the input to an array.

917

918 Parameters

919 ----------

920 a : array_like

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

922 includes lists, lists of tuples, tuples, tuples of tuples, tuples

923 of lists and ndarrays.

924 dtype : data-type, optional

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

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

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

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

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

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

931 'K' (keep) preserve input order

932 Defaults to 'K'.

933 ${ARRAY_FUNCTION_LIKE}

934

935 .. versionadded:: 1.20.0

936

937 Returns

938 -------

939 out : ndarray

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

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

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

943

944 See Also

945 --------

946 asanyarray : Similar function which passes through subclasses.

947 ascontiguousarray : Convert input to a contiguous array.

948 asfarray : Convert input to a floating point ndarray.

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

950 memory order.

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

952 fromiter : Create an array from an iterator.

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

954 positions.

955

956 Examples

957 --------

958 Convert a list into an array:

959

960 >>> a = [1, 2]

961 >>> np.asarray(a)

962 array([1, 2])

963

964 Existing arrays are not copied:

965

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

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

968 True

969

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

971

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

973 >>> np.asarray(a, dtype=np.float32) is a

974 True

975 >>> np.asarray(a, dtype=np.float64) is a

976 False

977

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

979

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

981 True

982 >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray)

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

984 False

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

986 True

987

988 """.replace(

989 "${ARRAY_FUNCTION_LIKE}",

990 array_function_like_doc,

991 ))

992

993 add_newdoc('numpy.core.multiarray', 'asanyarray',

994 """

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

996

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

998

999 Parameters

1000 ----------

1001 a : array_like

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

1003 includes scalars, lists, lists of tuples, tuples, tuples of tuples,

1004 tuples of lists, and ndarrays.

1005 dtype : data-type, optional

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

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

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

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

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

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

1012 'K' (keep) preserve input order

1013 Defaults to 'C'.

1014 ${ARRAY_FUNCTION_LIKE}

1015

1016 .. versionadded:: 1.20.0

1017

1018 Returns

1019 -------

1020 out : ndarray or an ndarray subclass

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

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

1023

1024 See Also

1025 --------

1026 asarray : Similar function which always returns ndarrays.

1027 ascontiguousarray : Convert input to a contiguous array.

1028 asfarray : Convert input to a floating point ndarray.

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

1030 memory order.

1031 asarray_chkfinite : Similar function which checks input for NaNs and

1032 Infs.

1033 fromiter : Create an array from an iterator.

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

1035 positions.

1036

1037 Examples

1038 --------

1039 Convert a list into an array:

1040

1041 >>> a = [1, 2]

1042 >>> np.asanyarray(a)

1043 array([1, 2])

1044

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

1046

1047 >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray)

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

1049 True

1050

1051 """.replace(

1052 "${ARRAY_FUNCTION_LIKE}",

1053 array_function_like_doc,

1054 ))

1055

1056 add_newdoc('numpy.core.multiarray', 'ascontiguousarray',

1057 """

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

1059

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

1061

1062 Parameters

1063 ----------

1064 a : array_like

1065 Input array.

1066 dtype : str or dtype object, optional

1067 Data-type of returned array.

1068 ${ARRAY_FUNCTION_LIKE}

1069

1070 .. versionadded:: 1.20.0

1071

1072 Returns

1073 -------

1074 out : ndarray

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

1076 if specified.

1077

1078 See Also

1079 --------

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

1081 memory order.

1082 require : Return an ndarray that satisfies requirements.

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

1084

1085 Examples

1086 --------

1087 Starting with a Fortran-contiguous array:

1088

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

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

1091 True

1092

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

1094

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

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

1097 True

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

1099 False

1100

1101 Now, starting with a C-contiguous array:

1102

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

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

1105 True

1106

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

1108

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

1110 >>> x is y

1111 True

1112

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

1114 so it will not preserve 0-d arrays.

1115

1116 """.replace(

1117 "${ARRAY_FUNCTION_LIKE}",

1118 array_function_like_doc,

1119 ))

1120

1121 add_newdoc('numpy.core.multiarray', 'asfortranarray',

1122 """

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

1124

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

1126

1127 Parameters

1128 ----------

1129 a : array_like

1130 Input array.

1131 dtype : str or dtype object, optional

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

1133 ${ARRAY_FUNCTION_LIKE}

1134

1135 .. versionadded:: 1.20.0

1136

1137 Returns

1138 -------

1139 out : ndarray

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

1141

1142 See Also

1143 --------

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

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

1146 column-major memory order.

1147 require : Return an ndarray that satisfies requirements.

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

1149

1150 Examples

1151 --------

1152 Starting with a C-contiguous array:

1153

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

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

1156 True

1157

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

1159

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

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

1162 True

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

1164 False

1165

1166 Now, starting with a Fortran-contiguous array:

1167

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

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

1170 True

1171

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

1173

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

1175 >>> x is y

1176 True

1177

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

1179 so it will not preserve 0-d arrays.

1180

1181 """.replace(

1182 "${ARRAY_FUNCTION_LIKE}",

1183 array_function_like_doc,

1184 ))

1185

1186 add_newdoc('numpy.core.multiarray', 'empty',

1187 """

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

1189

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

1191

1192 Parameters

1193 ----------

1194 shape : int or tuple of int

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

1196 dtype : data-type, optional

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

1198 `numpy.float64`.

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

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

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

1202 memory.

1203 ${ARRAY_FUNCTION_LIKE}

1204

1205 .. versionadded:: 1.20.0

1206

1207 Returns

1208 -------

1209 out : ndarray

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

1211 order. Object arrays will be initialized to None.

1212

1213 See Also

1214 --------

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

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

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

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

1219

1220

1221 Notes

1222 -----

1223 `empty`, unlike `zeros`, does not set the array values to zero,

1224 and may therefore be marginally faster. On the other hand, it requires

1225 the user to manually set all the values in the array, and should be

1226 used with caution.

1227

1228 Examples

1229 --------

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

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

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

1233

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

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

1236 [ 496041986, 19249760]]) #uninitialized

1237

1238 """.replace(

1239 "${ARRAY_FUNCTION_LIKE}",

1240 array_function_like_doc,

1241 ))

1242

1243 add_newdoc('numpy.core.multiarray', 'scalar',

1244 """

1245 scalar(dtype, obj)

1246

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

1248

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

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

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

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

1253 type and as zeros for all other types.

1254

1255 """)

1256

1257 add_newdoc('numpy.core.multiarray', 'zeros',

1258 """

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

1260

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

1262

1263 Parameters

1264 ----------

1265 shape : int or tuple of ints

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

1267 dtype : data-type, optional

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

1269 `numpy.float64`.

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

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

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

1273 memory.

1274 ${ARRAY_FUNCTION_LIKE}

1275

1276 .. versionadded:: 1.20.0

1277

1278 Returns

1279 -------

1280 out : ndarray

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

1282

1283 See Also

1284 --------

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

1286 empty : Return a new uninitialized array.

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

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

1289

1290 Examples

1291 --------

1292 >>> np.zeros(5)

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

1294

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

1296 array([0, 0, 0, 0, 0])

1297

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

1299 array([[ 0.],

1300 [ 0.]])

1301

1302 >>> s = (2,2)

1303 >>> np.zeros(s)

1304 array([[ 0., 0.],

1305 [ 0., 0.]])

1306

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

1308 array([(0, 0), (0, 0)],

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

1310

1311 """.replace(

1312 "${ARRAY_FUNCTION_LIKE}",

1313 array_function_like_doc,

1314 ))

1315

1316 add_newdoc('numpy.core.multiarray', 'set_typeDict',

1317 """set_typeDict(dict)

1318

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

1320 registered code.

1321

1322 """)

1323

1324 add_newdoc('numpy.core.multiarray', 'fromstring',

1325 """

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

1327

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

1329

1330 Parameters

1331 ----------

1332 string : str

1333 A string containing the data.

1334 dtype : data-type, optional

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

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

1337 supported and extension types may be supported.

1338

1339 .. versionadded:: 1.18.0

1340 Complex dtypes.

1341

1342 count : int, optional

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

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

1345 length of the data.

1346 sep : str, optional

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

1348 elements is also ignored.

1349

1350 .. deprecated:: 1.14

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

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

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

1354 decimal numbers, an operation which is better spelt

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

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

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

1358

1359 ${ARRAY_FUNCTION_LIKE}

1360

1361 .. versionadded:: 1.20.0

1362

1363 Returns

1364 -------

1365 arr : ndarray

1366 The constructed array.

1367

1368 Raises

1369 ------

1370 ValueError

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

1372 `dtype` and `count`.

1373

1374 See Also

1375 --------

1376 frombuffer, fromfile, fromiter

1377

1378 Examples

1379 --------

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

1381 array([1, 2])

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

1383 array([1, 2])

1384

1385 """.replace(

1386 "${ARRAY_FUNCTION_LIKE}",

1387 array_function_like_doc,

1388 ))

1389

1390 add_newdoc('numpy.core.multiarray', 'compare_chararrays',

1391 """

1392 compare_chararrays(a1, a2, cmp, rstrip)

1393

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

1395 comparison operator specified by `cmp_op`.

1396

1397 Parameters

1398 ----------

1399 a1, a2 : array_like

1400 Arrays to be compared.

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

1402 Type of comparison.

1403 rstrip : Boolean

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

1405

1406 Returns

1407 -------

1408 out : ndarray

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

1410

1411 Raises

1412 ------

1413 ValueError

1414 If `cmp_op` is not valid.

1415 TypeError

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

1417

1418 Examples

1419 --------

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

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

1422 >>> np.compare_chararrays(a, b, ">", True)

1423 array([False, True, False])

1424

1425 """)

1426

1427 add_newdoc('numpy.core.multiarray', 'fromiter',

1428 """

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

1430

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

1432

1433 Parameters

1434 ----------

1435 iter : iterable object

1436 An iterable object providing data for the array.

1437 dtype : data-type

1438 The data-type of the returned array.

1439

1440 .. versionchanged:: 1.23

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

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

1443

1444 count : int, optional

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

1446 which means all data is read.

1447 ${ARRAY_FUNCTION_LIKE}

1448

1449 .. versionadded:: 1.20.0

1450

1451 Returns

1452 -------

1453 out : ndarray

1454 The output array.

1455

1456 Notes

1457 -----

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

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

1460

1461 Examples

1462 --------

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

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

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

1466

1467 A carefully constructed subarray dtype will lead to higher dimensional

1468 results:

1469

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

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

1472 array([[1, 2],

1473 [2, 3],

1474 [3, 4],

1475 [4, 5],

1476 [5, 6]])

1477

1478

1479 """.replace(

1480 "${ARRAY_FUNCTION_LIKE}",

1481 array_function_like_doc,

1482 ))

1483

1484 add_newdoc('numpy.core.multiarray', 'fromfile',

1485 """

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

1487

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

1489

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

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

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

1493

1494 Parameters

1495 ----------

1496 file : file or str or Path

1497 Open file object or filename.

1498

1499 .. versionchanged:: 1.17.0

1500 `pathlib.Path` objects are now accepted.

1501

1502 dtype : data-type

1503 Data type of the returned array.

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

1505 of the items in the file.

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

1507

1508 .. versionadded:: 1.18.0

1509 Complex dtypes.

1510

1511 count : int

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

1513 file).

1514 sep : str

1515 Separator between items if file is a text file.

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

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

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

1519 whitespace.

1520 offset : int

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

1522 Only permitted for binary files.

1523

1524 .. versionadded:: 1.17.0

1525 ${ARRAY_FUNCTION_LIKE}

1526

1527 .. versionadded:: 1.20.0

1528

1529 See also

1530 --------

1531 load, save

1532 ndarray.tofile

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

1534

1535 Notes

1536 -----

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

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

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

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

1541 using `save` and `load` instead.

1542

1543 Examples

1544 --------

1545 Construct an ndarray:

1546

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

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

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

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

1551 >>> x

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

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

1554

1555 Save the raw data to disk:

1556

1557 >>> import tempfile

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

1559 >>> x.tofile(fname)

1560

1561 Read the raw data from disk:

1562

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

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

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

1566

1567 The recommended way to store and load data:

1568

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

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

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

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

1573

1574 """.replace(

1575 "${ARRAY_FUNCTION_LIKE}",

1576 array_function_like_doc,

1577 ))

1578

1579 add_newdoc('numpy.core.multiarray', 'frombuffer',

1580 """

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

1582

1583 Interpret a buffer as a 1-dimensional array.

1584

1585 Parameters

1586 ----------

1587 buffer : buffer_like

1588 An object that exposes the buffer interface.

1589 dtype : data-type, optional

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

1591 count : int, optional

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

1593 offset : int, optional

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

1595 ${ARRAY_FUNCTION_LIKE}

1596

1597 .. versionadded:: 1.20.0

1598

1599 Returns

1600 -------

1601 out : ndarray

1602

1603 See also

1604 --------

1605 ndarray.tobytes

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

1607 bytes in the array.

1608

1609 Notes

1610 -----

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

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

1613

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

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

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

1617

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

1619 interpreted correctly.

1620

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

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

1623 object is mutable or untrusted.

1624

1625 Examples

1626 --------

1627 >>> s = b'hello world'

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

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

1630

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

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

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

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

1635

1636 """.replace(

1637 "${ARRAY_FUNCTION_LIKE}",

1638 array_function_like_doc,

1639 ))

1640

1641 add_newdoc('numpy.core.multiarray', 'from_dlpack',

1642 """

1643 from_dlpack(x, /)

1644

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

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

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

1648

1649 Parameters

1650 ----------

1651 x : object

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

1653 ``__dlpack_device__`` methods.

1654

1655 Returns

1656 -------

1657 out : ndarray

1658

1659 References

1660 ----------

1661 .. [1] Array API documentation,

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

1663

1664 .. [2] Python specification for DLPack,

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

1666

1667 Examples

1668 --------

1669 >>> import torch

1670 >>> x = torch.arange(10)

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

1672 >>> y = np.from_dlpack(x)

1673 """)

1674

1675 add_newdoc('numpy.core', 'fastCopyAndTranspose',

1676 """

1677 fastCopyAndTranspose(a)

1678

1679 .. deprecated:: 1.24

1680

1681 fastCopyAndTranspose is deprecated and will be removed. Use the copy and

1682 transpose methods instead, e.g. ``arr.T.copy()``

1683 """)

1684

1685 add_newdoc('numpy.core.multiarray', 'correlate',

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

1687

1688 add_newdoc('numpy.core.multiarray', 'arange',

1689 """

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

1691

1692 Return evenly spaced values within a given interval.

1693

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

1695

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

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

1698 excluding `stop`).

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

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

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

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

1703 ``step``.

1704

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

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

1707 instance.

1708

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

1710 `numpy.linspace`.

1711

1712 See the Warning sections below for more information.

1713

1714 Parameters

1715 ----------

1716 start : integer or real, optional

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

1718 start value is 0.

1719 stop : integer or real

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

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

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

1723 step : integer or real, optional

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

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

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

1727 `start` must also be given.

1728 dtype : dtype, optional

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

1730 type from the other input arguments.

1731 ${ARRAY_FUNCTION_LIKE}

1732

1733 .. versionadded:: 1.20.0

1734

1735 Returns

1736 -------

1737 arange : ndarray

1738 Array of evenly spaced values.

1739

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

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

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

1743 than `stop`.

1744

1745 Warnings

1746 --------

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

1748

1749 Another stability issue is due to the internal implementation of

1750 `numpy.arange`.

1751 The actual step value used to populate the array is

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

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

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

1755 behaviour. For example::

1756

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

1758 array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

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

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

1761

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

1763

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

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

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

1767 incorrect results for large integer values::

1768

1769 >>> power = 40

1770 >>> modulo = 10000

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

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

1773 >>> print(x1)

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

1775 >>> print(x2)

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

1777

1778 See Also

1779 --------

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

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

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

1783 :ref:`how-to-partition`

1784

1785 Examples

1786 --------

1787 >>> np.arange(3)

1788 array([0, 1, 2])

1789 >>> np.arange(3.0)

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

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

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

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

1794 array([3, 5])

1795

1796 """.replace(

1797 "${ARRAY_FUNCTION_LIKE}",

1798 array_function_like_doc,

1799 ))

1800

1801 add_newdoc('numpy.core.multiarray', '_get_ndarray_c_version',

1802 """_get_ndarray_c_version()

1803

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

1805

1806 """)

1807

1808 add_newdoc('numpy.core.multiarray', '_reconstruct',

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

1810

1811 Construct an empty array. Used by Pickles.

1812

1813 """)

1814

1815

1816 add_newdoc('numpy.core.multiarray', 'set_string_function',

1817 """

1818 set_string_function(f, repr=1)

1819

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

1821

1822 """)

1823

1824 add_newdoc('numpy.core.multiarray', 'set_numeric_ops',

1825 """

1826 set_numeric_ops(op1=func1, op2=func2, ...)

1827

1828 Set numerical operators for array objects.

1829

1830 .. deprecated:: 1.16

1831

1832 For the general case, use :c:func:`PyUFunc_ReplaceLoopBySignature`.

1833 For ndarray subclasses, define the ``__array_ufunc__`` method and

1834 override the relevant ufunc.

1835

1836 Parameters

1837 ----------

1838 op1, op2, ... : callable

1839 Each ``op = func`` pair describes an operator to be replaced.

1840 For example, ``add = lambda x, y: np.add(x, y) % 5`` would replace

1841 addition by modulus 5 addition.

1842

1843 Returns

1844 -------

1845 saved_ops : list of callables

1846 A list of all operators, stored before making replacements.

1847

1848 Notes

1849 -----

1850 .. warning::

1851 Use with care! Incorrect usage may lead to memory errors.

1852

1853 A function replacing an operator cannot make use of that operator.

1854 For example, when replacing add, you may not use ``+``. Instead,

1855 directly call ufuncs.

1856

1857 Examples

1858 --------

1859 >>> def add_mod5(x, y):

1860 ... return np.add(x, y) % 5

1861 ...

1862 >>> old_funcs = np.set_numeric_ops(add=add_mod5)

1863

1864 >>> x = np.arange(12).reshape((3, 4))

1865 >>> x + x

1866 array([[0, 2, 4, 1],

1867 [3, 0, 2, 4],

1868 [1, 3, 0, 2]])

1869

1870 >>> ignore = np.set_numeric_ops(**old_funcs) # restore operators

1871

1872 """)

1873

1874 add_newdoc('numpy.core.multiarray', 'promote_types',

1875 """

1876 promote_types(type1, type2)

1877

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

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

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

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

1882

1883 This function is symmetric, but rarely associative.

1884

1885 Parameters

1886 ----------

1887 type1 : dtype or dtype specifier

1888 First data type.

1889 type2 : dtype or dtype specifier

1890 Second data type.

1891

1892 Returns

1893 -------

1894 out : dtype

1895 The promoted data type.

1896

1897 Notes

1898 -----

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

1900

1901 .. versionadded:: 1.6.0

1902

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

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

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

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

1907 converted to a string.

1908

1909 .. versionchanged:: 1.23.0

1910

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

1912 remove unnecessary padding from a structure dtype and promote included

1913 fields individually.

1914

1915 See Also

1916 --------

1917 result_type, dtype, can_cast

1918

1919 Examples

1920 --------

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

1922 dtype('float64')

1923

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

1925 dtype('float64')

1926

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

1928 dtype('complex128')

1929

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

1931 dtype('S11')

1932

1933 An example of a non-associative case:

1934

1935 >>> p = np.promote_types

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

1937 dtype('S6')

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

1939 dtype('S4')

1940

1941 """)

1942

1943 add_newdoc('numpy.core.multiarray', 'c_einsum',

1944 """

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

1946 casting='safe')

1947

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

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

1950

1951 Evaluates the Einstein summation convention on the operands.

1952

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

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

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

1956

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

1958 other array operations that might not be considered classical Einstein

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

1960 subscript labels.

1961

1962 See the notes and examples for clarification.

1963

1964 Parameters

1965 ----------

1966 subscripts : str

1967 Specifies the subscripts for summation as comma separated list of

1968 subscript labels. An implicit (classical Einstein summation)

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

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

1971 operands : list of array_like

1972 These are the arrays for the operation.

1973 out : ndarray, optional

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

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

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

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

1978 parameter to allow the conversions. Default is None.

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

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

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

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

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

1984 is possible, including arbitrarily permuted axes.

1985 Default is 'K'.

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

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

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

1989

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

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

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

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

1994 like float64 to float32, are allowed.

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

1996

1997 Default is 'safe'.

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

1999 Controls if intermediate optimization should occur. No optimization

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

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

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

2003

2004 Returns

2005 -------

2006 output : ndarray

2007 The calculation based on the Einstein summation convention.

2008

2009 See Also

2010 --------

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

2012

2013 Notes

2014 -----

2015 .. versionadded:: 1.6.0

2016

2017 The Einstein summation convention can be used to compute

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

2019 provides a succinct way of representing these.

2020

2021 A non-exhaustive list of these operations,

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

2023

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

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

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

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

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

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

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

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

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

2033

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

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

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

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

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

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

2040 describes traditional matrix multiplication and is equivalent to

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

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

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

2044

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

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

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

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

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

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

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

2052

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

2054 specifying output subscript labels. This requires the

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

2056 This feature increases the flexibility of the function since

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

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

2059 and ``np.einsum('ii->i', a)`` is like :py:func:`np.diag(a) <numpy.diag>`.

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

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

2062 order of the output subscript labels and therefore returns matrix

2063 multiplication, unlike the example above in implicit mode.

2064

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

2066 NumPy-style broadcasting is done by adding an ellipsis

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

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

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

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

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

2072

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

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

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

2076 produces a view (changed in version 1.10.0).

2077

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

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

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

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

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

2083 parameter methods.

2084

2085 .. versionadded:: 1.10.0

2086

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

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

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

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

2091 of a 2D array.

2092

2093 Examples

2094 --------

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

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

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

2098

2099 Trace of a matrix:

2100

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

2102 60

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

2104 60

2105 >>> np.trace(a)

2106 60

2107

2108 Extract the diagonal (requires explicit form):

2109

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

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

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

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

2114 >>> np.diag(a)

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

2116

2117 Sum over an axis (requires explicit form):

2118

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

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

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

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

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

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

2125

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

2127

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

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

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

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

2132

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

2134

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

2136 array([[0, 3],

2137 [1, 4],

2138 [2, 5]])

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

2140 array([[0, 3],

2141 [1, 4],

2142 [2, 5]])

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

2144 array([[0, 3],

2145 [1, 4],

2146 [2, 5]])

2147 >>> np.transpose(c)

2148 array([[0, 3],

2149 [1, 4],

2150 [2, 5]])

2151

2152 Vector inner products:

2153

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

2155 30

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

2157 30

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

2159 30

2160

2161 Matrix vector multiplication:

2162

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

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

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

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

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

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

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

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

2171

2172 Broadcasting and scalar multiplication:

2173

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

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

2176 [ 9, 12, 15]])

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

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

2179 [ 9, 12, 15]])

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

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

2182 [ 9, 12, 15]])

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

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

2185 [ 9, 12, 15]])

2186

2187 Vector outer product:

2188

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

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

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

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

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

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

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

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

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

2198

2199 Tensor contraction:

2200

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

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

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

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

2205 [ 4532., 4874.],

2206 [ 4664., 5018.],

2207 [ 4796., 5162.],

2208 [ 4928., 5306.]])

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

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

2211 [ 4532., 4874.],

2212 [ 4664., 5018.],

2213 [ 4796., 5162.],

2214 [ 4928., 5306.]])

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

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

2217 [ 4532., 4874.],

2218 [ 4664., 5018.],

2219 [ 4796., 5162.],

2220 [ 4928., 5306.]])

2221

2222 Writeable returned arrays (since version 1.10.0):

2223

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

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

2226 >>> a

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

2228 [ 0., 1., 0.],

2229 [ 0., 0., 1.]])

2230

2231 Example of ellipsis use:

2232

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

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

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

2236 array([[10, 28, 46, 64],

2237 [13, 40, 67, 94]])

2238 >>> np.einsum('ki,...k->i...', a, b)

2239 array([[10, 28, 46, 64],

2240 [13, 40, 67, 94]])

2241 >>> np.einsum('k...,jk', a, b)

2242 array([[10, 28, 46, 64],

2243 [13, 40, 67, 94]])

2244

2245 """)

2246

2247

2248##############################################################################

2249#

2250# Documentation for ndarray attributes and methods

2251#

2252##############################################################################

2253

2254

2255##############################################################################

2256#

2257# ndarray object

2258#

2259##############################################################################

2260

2261

2262 add_newdoc('numpy.core.multiarray', 'ndarray',

2263 """

2264 ndarray(shape, dtype=float, buffer=None, offset=0,

2265 strides=None, order=None)

2266

2267 An array object represents a multidimensional, homogeneous array

2268 of fixed-size items. An associated data-type object describes the

2269 format of each element in the array (its byte-order, how many bytes it

2270 occupies in memory, whether it is an integer, a floating point number,

2271 or something else, etc.)

2272

2273 Arrays should be constructed using `array`, `zeros` or `empty` (refer

2274 to the See Also section below). The parameters given here refer to

2275 a low-level method (`ndarray(...)`) for instantiating an array.

2276

2277 For more information, refer to the `numpy` module and examine the

2278 methods and attributes of an array.

2279

2280 Parameters

2281 ----------

2282 (for the __new__ method; see Notes below)

2283

2284 shape : tuple of ints

2285 Shape of created array.

2286 dtype : data-type, optional

2287 Any object that can be interpreted as a numpy data type.

2288 buffer : object exposing buffer interface, optional

2289 Used to fill the array with data.

2290 offset : int, optional

2291 Offset of array data in buffer.

2292 strides : tuple of ints, optional

2293 Strides of data in memory.

2294 order : {'C', 'F'}, optional

2295 Row-major (C-style) or column-major (Fortran-style) order.

2296

2297 Attributes

2298 ----------

2299 T : ndarray

2300 Transpose of the array.

2301 data : buffer

2302 The array's elements, in memory.

2303 dtype : dtype object

2304 Describes the format of the elements in the array.

2305 flags : dict

2306 Dictionary containing information related to memory use, e.g.,

2307 'C_CONTIGUOUS', 'OWNDATA', 'WRITEABLE', etc.

2308 flat : numpy.flatiter object

2309 Flattened version of the array as an iterator. The iterator

2310 allows assignments, e.g., ``x.flat = 3`` (See `ndarray.flat` for

2311 assignment examples; TODO).

2312 imag : ndarray

2313 Imaginary part of the array.

2314 real : ndarray

2315 Real part of the array.

2316 size : int

2317 Number of elements in the array.

2318 itemsize : int

2319 The memory use of each array element in bytes.

2320 nbytes : int

2321 The total number of bytes required to store the array data,

2322 i.e., ``itemsize * size``.

2323 ndim : int

2324 The array's number of dimensions.

2325 shape : tuple of ints

2326 Shape of the array.

2327 strides : tuple of ints

2328 The step-size required to move from one element to the next in

2329 memory. For example, a contiguous ``(3, 4)`` array of type

2330 ``int16`` in C-order has strides ``(8, 2)``. This implies that

2331 to move from element to element in memory requires jumps of 2 bytes.

2332 To move from row-to-row, one needs to jump 8 bytes at a time

2333 (``2 * 4``).

2334 ctypes : ctypes object

2335 Class containing properties of the array needed for interaction

2336 with ctypes.

2337 base : ndarray

2338 If the array is a view into another array, that array is its `base`

2339 (unless that array is also a view). The `base` array is where the

2340 array data is actually stored.

2341

2342 See Also

2343 --------

2344 array : Construct an array.

2345 zeros : Create an array, each element of which is zero.

2346 empty : Create an array, but leave its allocated memory unchanged (i.e.,

2347 it contains "garbage").

2348 dtype : Create a data-type.

2349 numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>`

2350 w.r.t. its `dtype.type <numpy.dtype.type>`.

2351

2352 Notes

2353 -----

2354 There are two modes of creating an array using ``__new__``:

2355

2356 1. If `buffer` is None, then only `shape`, `dtype`, and `order`

2357 are used.

2358 2. If `buffer` is an object exposing the buffer interface, then

2359 all keywords are interpreted.

2360

2361 No ``__init__`` method is needed because the array is fully initialized

2362 after the ``__new__`` method.

2363

2364 Examples

2365 --------

2366 These examples illustrate the low-level `ndarray` constructor. Refer

2367 to the `See Also` section above for easier ways of constructing an

2368 ndarray.

2369

2370 First mode, `buffer` is None:

2371

2372 >>> np.ndarray(shape=(2,2), dtype=float, order='F')

2373 array([[0.0e+000, 0.0e+000], # random

2374 [ nan, 2.5e-323]])

2375

2376 Second mode:

2377

2378 >>> np.ndarray((2,), buffer=np.array([1,2,3]),

2379 ... offset=np.int_().itemsize,

2380 ... dtype=int) # offset = 1*itemsize, i.e. skip first element

2381 array([2, 3])

2382

2383 """)

2384

2385

2386##############################################################################

2387#

2388# ndarray attributes

2389#

2390##############################################################################

2391

2392

2393 add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_interface__',

2394 """Array protocol: Python side."""))

2395

2396

2397 add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_priority__',

2398 """Array priority."""))

2399

2400

2401 add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_struct__',

2402 """Array protocol: C-struct side."""))

2403

2404 add_newdoc('numpy.core.multiarray', 'ndarray', ('__dlpack__',

2405 """a.__dlpack__(*, stream=None)

2406

2407 DLPack Protocol: Part of the Array API."""))

2408

2409 add_newdoc('numpy.core.multiarray', 'ndarray', ('__dlpack_device__',

2410 """a.__dlpack_device__()

2411

2412 DLPack Protocol: Part of the Array API."""))

2413

2414 add_newdoc('numpy.core.multiarray', 'ndarray', ('base',

2415 """

2416 Base object if memory is from some other object.

2417

2418 Examples

2419 --------

2420 The base of an array that owns its memory is None:

2421

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

2423 >>> x.base is None

2424 True

2425

2426 Slicing creates a view, whose memory is shared with x:

2427

2428 >>> y = x[2:]

2429 >>> y.base is x

2430 True

2431

2432 """))

2433

2434

2435 add_newdoc('numpy.core.multiarray', 'ndarray', ('ctypes',

2436 """

2437 An object to simplify the interaction of the array with the ctypes

2438 module.

2439

2440 This attribute creates an object that makes it easier to use arrays

2441 when calling shared libraries with the ctypes module. The returned

2442 object has, among others, data, shape, and strides attributes (see

2443 Notes below) which themselves return ctypes objects that can be used

2444 as arguments to a shared library.

2445

2446 Parameters

2447 ----------

2448 None

2449

2450 Returns

2451 -------

2452 c : Python object

2453 Possessing attributes data, shape, strides, etc.

2454

2455 See Also

2456 --------

2457 numpy.ctypeslib

2458

2459 Notes

2460 -----

2461 Below are the public attributes of this object which were documented

2462 in "Guide to NumPy" (we have omitted undocumented public attributes,

2463 as well as documented private attributes):

2464

2465 .. autoattribute:: numpy.core._internal._ctypes.data

2466 :noindex:

2467

2468 .. autoattribute:: numpy.core._internal._ctypes.shape

2469 :noindex:

2470

2471 .. autoattribute:: numpy.core._internal._ctypes.strides

2472 :noindex:

2473

2474 .. automethod:: numpy.core._internal._ctypes.data_as

2475 :noindex:

2476

2477 .. automethod:: numpy.core._internal._ctypes.shape_as

2478 :noindex:

2479

2480 .. automethod:: numpy.core._internal._ctypes.strides_as

2481 :noindex:

2482

2483 If the ctypes module is not available, then the ctypes attribute

2484 of array objects still returns something useful, but ctypes objects

2485 are not returned and errors may be raised instead. In particular,

2486 the object will still have the ``as_parameter`` attribute which will

2487 return an integer equal to the data attribute.

2488

2489 Examples

2490 --------

2491 >>> import ctypes

2492 >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)

2493 >>> x

2494 array([[0, 1],

2495 [2, 3]], dtype=int32)

2496 >>> x.ctypes.data

2497 31962608 # may vary

2498 >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))

2499 <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary

2500 >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents

2501 c_uint(0)

2502 >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents

2503 c_ulong(4294967296)

2504 >>> x.ctypes.shape

2505 <numpy.core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary

2506 >>> x.ctypes.strides

2507 <numpy.core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary

2508

2509 """))

2510

2511

2512 add_newdoc('numpy.core.multiarray', 'ndarray', ('data',

2513 """Python buffer object pointing to the start of the array's data."""))

2514

2515

2516 add_newdoc('numpy.core.multiarray', 'ndarray', ('dtype',

2517 """

2518 Data-type of the array's elements.

2519

2520 .. warning::

2521

2522 Setting ``arr.dtype`` is discouraged and may be deprecated in the

2523 future. Setting will replace the ``dtype`` without modifying the

2524 memory (see also `ndarray.view` and `ndarray.astype`).

2525

2526 Parameters

2527 ----------

2528 None

2529

2530 Returns

2531 -------

2532 d : numpy dtype object

2533

2534 See Also

2535 --------

2536 ndarray.astype : Cast the values contained in the array to a new data-type.

2537 ndarray.view : Create a view of the same data but a different data-type.

2538 numpy.dtype

2539

2540 Examples

2541 --------

2542 >>> x

2543 array([[0, 1],

2544 [2, 3]])

2545 >>> x.dtype

2546 dtype('int32')

2547 >>> type(x.dtype)

2548 <type 'numpy.dtype'>

2549

2550 """))

2551

2552

2553 add_newdoc('numpy.core.multiarray', 'ndarray', ('imag',

2554 """

2555 The imaginary part of the array.

2556

2557 Examples

2558 --------

2559 >>> x = np.sqrt([1+0j, 0+1j])

2560 >>> x.imag

2561 array([ 0. , 0.70710678])

2562 >>> x.imag.dtype

2563 dtype('float64')

2564

2565 """))

2566

2567

2568 add_newdoc('numpy.core.multiarray', 'ndarray', ('itemsize',

2569 """

2570 Length of one array element in bytes.

2571

2572 Examples

2573 --------

2574 >>> x = np.array([1,2,3], dtype=np.float64)

2575 >>> x.itemsize

2576 8

2577 >>> x = np.array([1,2,3], dtype=np.complex128)

2578 >>> x.itemsize

2579 16

2580

2581 """))

2582

2583

2584 add_newdoc('numpy.core.multiarray', 'ndarray', ('flags',

2585 """

2586 Information about the memory layout of the array.

2587

2588 Attributes

2589 ----------

2590 C_CONTIGUOUS (C)

2591 The data is in a single, C-style contiguous segment.

2592 F_CONTIGUOUS (F)

2593 The data is in a single, Fortran-style contiguous segment.

2594 OWNDATA (O)

2595 The array owns the memory it uses or borrows it from another object.

2596 WRITEABLE (W)

2597 The data area can be written to. Setting this to False locks

2598 the data, making it read-only. A view (slice, etc.) inherits WRITEABLE

2599 from its base array at creation time, but a view of a writeable

2600 array may be subsequently locked while the base array remains writeable.

2601 (The opposite is not true, in that a view of a locked array may not

2602 be made writeable. However, currently, locking a base object does not

2603 lock any views that already reference it, so under that circumstance it

2604 is possible to alter the contents of a locked array via a previously

2605 created writeable view onto it.) Attempting to change a non-writeable

2606 array raises a RuntimeError exception.

2607 ALIGNED (A)

2608 The data and all elements are aligned appropriately for the hardware.

2609 WRITEBACKIFCOPY (X)

2610 This array is a copy of some other array. The C-API function

2611 PyArray_ResolveWritebackIfCopy must be called before deallocating

2612 to the base array will be updated with the contents of this array.

2613 FNC

2614 F_CONTIGUOUS and not C_CONTIGUOUS.

2615 FORC

2616 F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).

2617 BEHAVED (B)

2618 ALIGNED and WRITEABLE.

2619 CARRAY (CA)

2620 BEHAVED and C_CONTIGUOUS.

2621 FARRAY (FA)

2622 BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.

2623

2624 Notes

2625 -----

2626 The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),

2627 or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag

2628 names are only supported in dictionary access.

2629

2630 Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be

2631 changed by the user, via direct assignment to the attribute or dictionary

2632 entry, or by calling `ndarray.setflags`.

2633

2634 The array flags cannot be set arbitrarily:

2635

2636 - WRITEBACKIFCOPY can only be set ``False``.

2637 - ALIGNED can only be set ``True`` if the data is truly aligned.

2638 - WRITEABLE can only be set ``True`` if the array owns its own memory

2639 or the ultimate owner of the memory exposes a writeable buffer

2640 interface or is a string.

2641

2642 Arrays can be both C-style and Fortran-style contiguous simultaneously.

2643 This is clear for 1-dimensional arrays, but can also be true for higher

2644 dimensional arrays.

2645

2646 Even for contiguous arrays a stride for a given dimension

2647 ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``

2648 or the array has no elements.

2649 It does *not* generally hold that ``self.strides[-1] == self.itemsize``

2650 for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for

2651 Fortran-style contiguous arrays is true.

2652 """))

2653

2654

2655 add_newdoc('numpy.core.multiarray', 'ndarray', ('flat',

2656 """

2657 A 1-D iterator over the array.

2658

2659 This is a `numpy.flatiter` instance, which acts similarly to, but is not

2660 a subclass of, Python's built-in iterator object.

2661

2662 See Also

2663 --------

2664 flatten : Return a copy of the array collapsed into one dimension.

2665

2666 flatiter

2667

2668 Examples

2669 --------

2670 >>> x = np.arange(1, 7).reshape(2, 3)

2671 >>> x

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

2673 [4, 5, 6]])

2674 >>> x.flat[3]

2675 4

2676 >>> x.T

2677 array([[1, 4],

2678 [2, 5],

2679 [3, 6]])

2680 >>> x.T.flat[3]

2681 5

2682 >>> type(x.flat)

2683 <class 'numpy.flatiter'>

2684

2685 An assignment example:

2686

2687 >>> x.flat = 3; x

2688 array([[3, 3, 3],

2689 [3, 3, 3]])

2690 >>> x.flat[[1,4]] = 1; x

2691 array([[3, 1, 3],

2692 [3, 1, 3]])

2693

2694 """))

2695

2696

2697 add_newdoc('numpy.core.multiarray', 'ndarray', ('nbytes',

2698 """

2699 Total bytes consumed by the elements of the array.

2700

2701 Notes

2702 -----

2703 Does not include memory consumed by non-element attributes of the

2704 array object.

2705

2706 Examples

2707 --------

2708 >>> x = np.zeros((3,5,2), dtype=np.complex128)

2709 >>> x.nbytes

2710 480

2711 >>> np.prod(x.shape) * x.itemsize

2712 480

2713

2714 """))

2715

2716

2717 add_newdoc('numpy.core.multiarray', 'ndarray', ('ndim',

2718 """

2719 Number of array dimensions.

2720

2721 Examples

2722 --------

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

2724 >>> x.ndim

2725 1

2726 >>> y = np.zeros((2, 3, 4))

2727 >>> y.ndim

2728 3

2729

2730 """))

2731

2732

2733 add_newdoc('numpy.core.multiarray', 'ndarray', ('real',

2734 """

2735 The real part of the array.

2736

2737 Examples

2738 --------

2739 >>> x = np.sqrt([1+0j, 0+1j])

2740 >>> x.real

2741 array([ 1. , 0.70710678])

2742 >>> x.real.dtype

2743 dtype('float64')

2744

2745 See Also

2746 --------

2747 numpy.real : equivalent function

2748

2749 """))

2750

2751

2752 add_newdoc('numpy.core.multiarray', 'ndarray', ('shape',

2753 """

2754 Tuple of array dimensions.

2755

2756 The shape property is usually used to get the current shape of an array,

2757 but may also be used to reshape the array in-place by assigning a tuple of

2758 array dimensions to it. As with `numpy.reshape`, one of the new shape

2759 dimensions can be -1, in which case its value is inferred from the size of

2760 the array and the remaining dimensions. Reshaping an array in-place will

2761 fail if a copy is required.

2762

2763 .. warning::

2764

2765 Setting ``arr.shape`` is discouraged and may be deprecated in the

2766 future. Using `ndarray.reshape` is the preferred approach.

2767

2768 Examples

2769 --------

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

2771 >>> x.shape

2772 (4,)

2773 >>> y = np.zeros((2, 3, 4))

2774 >>> y.shape

2775 (2, 3, 4)

2776 >>> y.shape = (3, 8)

2777 >>> y

2778 array([[ 0., 0., 0., 0., 0., 0., 0., 0.],

2779 [ 0., 0., 0., 0., 0., 0., 0., 0.],

2780 [ 0., 0., 0., 0., 0., 0., 0., 0.]])

2781 >>> y.shape = (3, 6)

2782 Traceback (most recent call last):

2783 File "<stdin>", line 1, in <module>

2784 ValueError: total size of new array must be unchanged

2785 >>> np.zeros((4,2))[::2].shape = (-1,)

2786 Traceback (most recent call last):

2787 File "<stdin>", line 1, in <module>

2788 AttributeError: Incompatible shape for in-place modification. Use

2789 `.reshape()` to make a copy with the desired shape.

2790

2791 See Also

2792 --------

2793 numpy.shape : Equivalent getter function.

2794 numpy.reshape : Function similar to setting ``shape``.

2795 ndarray.reshape : Method similar to setting ``shape``.

2796

2797 """))

2798

2799

2800 add_newdoc('numpy.core.multiarray', 'ndarray', ('size',

2801 """

2802 Number of elements in the array.

2803

2804 Equal to ``np.prod(a.shape)``, i.e., the product of the array's

2805 dimensions.

2806

2807 Notes

2808 -----

2809 `a.size` returns a standard arbitrary precision Python integer. This

2810 may not be the case with other methods of obtaining the same value

2811 (like the suggested ``np.prod(a.shape)``, which returns an instance

2812 of ``np.int_``), and may be relevant if the value is used further in

2813 calculations that may overflow a fixed size integer type.

2814

2815 Examples

2816 --------

2817 >>> x = np.zeros((3, 5, 2), dtype=np.complex128)

2818 >>> x.size

2819 30

2820 >>> np.prod(x.shape)

2821 30

2822

2823 """))

2824

2825

2826 add_newdoc('numpy.core.multiarray', 'ndarray', ('strides',

2827 """

2828 Tuple of bytes to step in each dimension when traversing an array.

2829

2830 The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`

2831 is::

2832

2833 offset = sum(np.array(i) * a.strides)

2834

2835 A more detailed explanation of strides can be found in the

2836 "ndarray.rst" file in the NumPy reference guide.

2837

2838 .. warning::

2839

2840 Setting ``arr.strides`` is discouraged and may be deprecated in the

2841 future. `numpy.lib.stride_tricks.as_strided` should be preferred

2842 to create a new view of the same data in a safer way.

2843

2844 Notes

2845 -----

2846 Imagine an array of 32-bit integers (each 4 bytes)::

2847

2848 x = np.array([[0, 1, 2, 3, 4],

2849 [5, 6, 7, 8, 9]], dtype=np.int32)

2850

2851 This array is stored in memory as 40 bytes, one after the other

2852 (known as a contiguous block of memory). The strides of an array tell

2853 us how many bytes we have to skip in memory to move to the next position

2854 along a certain axis. For example, we have to skip 4 bytes (1 value) to

2855 move to the next column, but 20 bytes (5 values) to get to the same

2856 position in the next row. As such, the strides for the array `x` will be

2857 ``(20, 4)``.

2858

2859 See Also

2860 --------

2861 numpy.lib.stride_tricks.as_strided

2862

2863 Examples

2864 --------

2865 >>> y = np.reshape(np.arange(2*3*4), (2,3,4))

2866 >>> y

2867 array([[[ 0, 1, 2, 3],

2868 [ 4, 5, 6, 7],

2869 [ 8, 9, 10, 11]],

2870 [[12, 13, 14, 15],

2871 [16, 17, 18, 19],

2872 [20, 21, 22, 23]]])

2873 >>> y.strides

2874 (48, 16, 4)

2875 >>> y[1,1,1]

2876 17

2877 >>> offset=sum(y.strides * np.array((1,1,1)))

2878 >>> offset/y.itemsize

2879 17

2880

2881 >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)

2882 >>> x.strides

2883 (32, 4, 224, 1344)

2884 >>> i = np.array([3,5,2,2])

2885 >>> offset = sum(i * x.strides)

2886 >>> x[3,5,2,2]

2887 813

2888 >>> offset / x.itemsize

2889 813

2890

2891 """))

2892

2893

2894 add_newdoc('numpy.core.multiarray', 'ndarray', ('T',

2895 """

2896 View of the transposed array.

2897

2898 Same as ``self.transpose()``.

2899

2900 Examples

2901 --------

2902 >>> a = np.array([[1, 2], [3, 4]])

2903 >>> a

2904 array([[1, 2],

2905 [3, 4]])

2906 >>> a.T

2907 array([[1, 3],

2908 [2, 4]])

2909

2910 >>> a = np.array([1, 2, 3, 4])

2911 >>> a

2912 array([1, 2, 3, 4])

2913 >>> a.T

2914 array([1, 2, 3, 4])

2915

2916 See Also

2917 --------

2918 transpose

2919

2920 """))

2921

2922

2923##############################################################################

2924#

2925# ndarray methods

2926#

2927##############################################################################

2928

2929

2930 add_newdoc('numpy.core.multiarray', 'ndarray', ('__array__',

2931 """ a.__array__([dtype], /) -> reference if type unchanged, copy otherwise.

2932

2933 Returns either a new reference to self if dtype is not given or a new array

2934 of provided data type if dtype is different from the current dtype of the

2935 array.

2936

2937 """))

2938

2939

2940 add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_finalize__',

2941 """a.__array_finalize__(obj, /)

2942

2943 Present so subclasses can call super. Does nothing.

2944

2945 """))

2946

2947

2948 add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_prepare__',

2949 """a.__array_prepare__(array[, context], /)

2950

2951 Returns a view of `array` with the same type as self.

2952

2953 """))

2954

2955

2956 add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_wrap__',

2957 """a.__array_wrap__(array[, context], /)

2958

2959 Returns a view of `array` with the same type as self.

2960

2961 """))

2962

2963

2964 add_newdoc('numpy.core.multiarray', 'ndarray', ('__copy__',

2965 """a.__copy__()

2966

2967 Used if :func:`copy.copy` is called on an array. Returns a copy of the array.

2968

2969 Equivalent to ``a.copy(order='K')``.

2970

2971 """))

2972

2973

2974 add_newdoc('numpy.core.multiarray', 'ndarray', ('__class_getitem__',

2975 """a.__class_getitem__(item, /)

2976

2977 Return a parametrized wrapper around the `~numpy.ndarray` type.

2978

2979 .. versionadded:: 1.22

2980

2981 Returns

2982 -------

2983 alias : types.GenericAlias

2984 A parametrized `~numpy.ndarray` type.

2985

2986 Examples

2987 --------

2988 >>> from typing import Any

2989 >>> import numpy as np

2990

2991 >>> np.ndarray[Any, np.dtype[Any]]

2992 numpy.ndarray[typing.Any, numpy.dtype[typing.Any]]

2993

2994 Notes

2995 -----

2996 This method is only available for python 3.9 and later.

2997

2998 See Also

2999 --------

3000 :pep:`585` : Type hinting generics in standard collections.

3001 numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>`

3002 w.r.t. its `dtype.type <numpy.dtype.type>`.

3003

3004 """))

3005

3006

3007 add_newdoc('numpy.core.multiarray', 'ndarray', ('__deepcopy__',

3008 """a.__deepcopy__(memo, /) -> Deep copy of array.

3009

3010 Used if :func:`copy.deepcopy` is called on an array.

3011

3012 """))

3013

3014

3015 add_newdoc('numpy.core.multiarray', 'ndarray', ('__reduce__',

3016 """a.__reduce__()

3017

3018 For pickling.

3019

3020 """))

3021

3022

3023 add_newdoc('numpy.core.multiarray', 'ndarray', ('__setstate__',

3024 """a.__setstate__(state, /)

3025

3026 For unpickling.

3027

3028 The `state` argument must be a sequence that contains the following

3029 elements:

3030

3031 Parameters

3032 ----------

3033 version : int

3034 optional pickle version. If omitted defaults to 0.

3035 shape : tuple

3036 dtype : data-type

3037 isFortran : bool

3038 rawdata : string or list

3039 a binary string with the data (or a list if 'a' is an object array)

3040

3041 """))

3042

3043

3044 add_newdoc('numpy.core.multiarray', 'ndarray', ('all',

3045 """

3046 a.all(axis=None, out=None, keepdims=False, *, where=True)

3047

3048 Returns True if all elements evaluate to True.

3049

3050 Refer to `numpy.all` for full documentation.

3051

3052 See Also

3053 --------

3054 numpy.all : equivalent function

3055

3056 """))

3057

3058

3059 add_newdoc('numpy.core.multiarray', 'ndarray', ('any',

3060 """

3061 a.any(axis=None, out=None, keepdims=False, *, where=True)

3062

3063 Returns True if any of the elements of `a` evaluate to True.

3064

3065 Refer to `numpy.any` for full documentation.

3066

3067 See Also

3068 --------

3069 numpy.any : equivalent function

3070

3071 """))

3072

3073

3074 add_newdoc('numpy.core.multiarray', 'ndarray', ('argmax',

3075 """

3076 a.argmax(axis=None, out=None, *, keepdims=False)

3077

3078 Return indices of the maximum values along the given axis.

3079

3080 Refer to `numpy.argmax` for full documentation.

3081

3082 See Also

3083 --------

3084 numpy.argmax : equivalent function

3085

3086 """))

3087

3088

3089 add_newdoc('numpy.core.multiarray', 'ndarray', ('argmin',

3090 """

3091 a.argmin(axis=None, out=None, *, keepdims=False)

3092

3093 Return indices of the minimum values along the given axis.

3094

3095 Refer to `numpy.argmin` for detailed documentation.

3096

3097 See Also

3098 --------

3099 numpy.argmin : equivalent function

3100

3101 """))

3102

3103

3104 add_newdoc('numpy.core.multiarray', 'ndarray', ('argsort',

3105 """

3106 a.argsort(axis=-1, kind=None, order=None)

3107

3108 Returns the indices that would sort this array.

3109

3110 Refer to `numpy.argsort` for full documentation.

3111

3112 See Also

3113 --------

3114 numpy.argsort : equivalent function

3115

3116 """))

3117

3118

3119 add_newdoc('numpy.core.multiarray', 'ndarray', ('argpartition',

3120 """

3121 a.argpartition(kth, axis=-1, kind='introselect', order=None)

3122

3123 Returns the indices that would partition this array.

3124

3125 Refer to `numpy.argpartition` for full documentation.

3126

3127 .. versionadded:: 1.8.0

3128

3129 See Also

3130 --------

3131 numpy.argpartition : equivalent function

3132

3133 """))

3134

3135

3136 add_newdoc('numpy.core.multiarray', 'ndarray', ('astype',

3137 """

3138 a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)

3139

3140 Copy of the array, cast to a specified type.

3141

3142 Parameters

3143 ----------

3144 dtype : str or dtype

3145 Typecode or data-type to which the array is cast.

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

3147 Controls the memory layout order of the result.

3148 'C' means C order, 'F' means Fortran order, 'A'

3149 means 'F' order if all the arrays are Fortran contiguous,

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

3151 order the array elements appear in memory as possible.

3152 Default is 'K'.

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

3154 Controls what kind of data casting may occur. Defaults to 'unsafe'

3155 for backwards compatibility.

3156

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

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

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

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

3161 like float64 to float32, are allowed.

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

3163 subok : bool, optional

3164 If True, then sub-classes will be passed-through (default), otherwise

3165 the returned array will be forced to be a base-class array.

3166 copy : bool, optional

3167 By default, astype always returns a newly allocated array. If this

3168 is set to false, and the `dtype`, `order`, and `subok`

3169 requirements are satisfied, the input array is returned instead

3170 of a copy.

3171

3172 Returns

3173 -------

3174 arr_t : ndarray

3175 Unless `copy` is False and the other conditions for returning the input

3176 array are satisfied (see description for `copy` input parameter), `arr_t`

3177 is a new array of the same shape as the input array, with dtype, order

3178 given by `dtype`, `order`.

3179

3180 Notes

3181 -----

3182 .. versionchanged:: 1.17.0

3183 Casting between a simple data type and a structured one is possible only

3184 for "unsafe" casting. Casting to multiple fields is allowed, but

3185 casting from multiple fields is not.

3186

3187 .. versionchanged:: 1.9.0

3188 Casting from numeric to string types in 'safe' casting mode requires

3189 that the string dtype length is long enough to store the max

3190 integer/float value converted.

3191

3192 Raises

3193 ------

3194 ComplexWarning

3195 When casting from complex to float or int. To avoid this,

3196 one should use ``a.real.astype(t)``.

3197

3198 Examples

3199 --------

3200 >>> x = np.array([1, 2, 2.5])

3201 >>> x

3202 array([1. , 2. , 2.5])

3203

3204 >>> x.astype(int)

3205 array([1, 2, 2])

3206

3207 """))

3208

3209

3210 add_newdoc('numpy.core.multiarray', 'ndarray', ('byteswap',

3211 """

3212 a.byteswap(inplace=False)

3213

3214 Swap the bytes of the array elements

3215

3216 Toggle between low-endian and big-endian data representation by

3217 returning a byteswapped array, optionally swapped in-place.

3218 Arrays of byte-strings are not swapped. The real and imaginary

3219 parts of a complex number are swapped individually.

3220

3221 Parameters

3222 ----------

3223 inplace : bool, optional

3224 If ``True``, swap bytes in-place, default is ``False``.

3225

3226 Returns

3227 -------

3228 out : ndarray

3229 The byteswapped array. If `inplace` is ``True``, this is

3230 a view to self.

3231

3232 Examples

3233 --------

3234 >>> A = np.array([1, 256, 8755], dtype=np.int16)

3235 >>> list(map(hex, A))

3236 ['0x1', '0x100', '0x2233']

3237 >>> A.byteswap(inplace=True)

3238 array([ 256, 1, 13090], dtype=int16)

3239 >>> list(map(hex, A))

3240 ['0x100', '0x1', '0x3322']

3241

3242 Arrays of byte-strings are not swapped

3243

3244 >>> A = np.array([b'ceg', b'fac'])

3245 >>> A.byteswap()

3246 array([b'ceg', b'fac'], dtype='|S3')

3247

3248 ``A.newbyteorder().byteswap()`` produces an array with the same values

3249 but different representation in memory

3250

3251 >>> A = np.array([1, 2, 3])

3252 >>> A.view(np.uint8)

3253 array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,

3254 0, 0], dtype=uint8)

3255 >>> A.newbyteorder().byteswap(inplace=True)

3256 array([1, 2, 3])

3257 >>> A.view(np.uint8)

3258 array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,

3259 0, 3], dtype=uint8)

3260

3261 """))

3262

3263

3264 add_newdoc('numpy.core.multiarray', 'ndarray', ('choose',

3265 """

3266 a.choose(choices, out=None, mode='raise')

3267

3268 Use an index array to construct a new array from a set of choices.

3269

3270 Refer to `numpy.choose` for full documentation.

3271

3272 See Also

3273 --------

3274 numpy.choose : equivalent function

3275

3276 """))

3277

3278

3279 add_newdoc('numpy.core.multiarray', 'ndarray', ('clip',

3280 """

3281 a.clip(min=None, max=None, out=None, **kwargs)

3282

3283 Return an array whose values are limited to ``[min, max]``.

3284 One of max or min must be given.

3285

3286 Refer to `numpy.clip` for full documentation.

3287

3288 See Also

3289 --------

3290 numpy.clip : equivalent function

3291

3292 """))

3293

3294

3295 add_newdoc('numpy.core.multiarray', 'ndarray', ('compress',

3296 """

3297 a.compress(condition, axis=None, out=None)

3298

3299 Return selected slices of this array along given axis.

3300

3301 Refer to `numpy.compress` for full documentation.

3302

3303 See Also

3304 --------

3305 numpy.compress : equivalent function

3306

3307 """))

3308

3309

3310 add_newdoc('numpy.core.multiarray', 'ndarray', ('conj',

3311 """

3312 a.conj()

3313

3314 Complex-conjugate all elements.

3315

3316 Refer to `numpy.conjugate` for full documentation.

3317

3318 See Also

3319 --------

3320 numpy.conjugate : equivalent function

3321

3322 """))

3323

3324

3325 add_newdoc('numpy.core.multiarray', 'ndarray', ('conjugate',

3326 """

3327 a.conjugate()

3328

3329 Return the complex conjugate, element-wise.

3330

3331 Refer to `numpy.conjugate` for full documentation.

3332

3333 See Also

3334 --------

3335 numpy.conjugate : equivalent function

3336

3337 """))

3338

3339

3340 add_newdoc('numpy.core.multiarray', 'ndarray', ('copy',

3341 """

3342 a.copy(order='C')

3343

3344 Return a copy of the array.

3345

3346 Parameters

3347 ----------

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

3349 Controls the memory layout of the copy. 'C' means C-order,

3350 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,

3351 'C' otherwise. 'K' means match the layout of `a` as closely

3352 as possible. (Note that this function and :func:`numpy.copy` are very

3353 similar but have different default values for their order=

3354 arguments, and this function always passes sub-classes through.)

3355

3356 See also

3357 --------

3358 numpy.copy : Similar function with different default behavior

3359 numpy.copyto

3360

3361 Notes

3362 -----

3363 This function is the preferred method for creating an array copy. The

3364 function :func:`numpy.copy` is similar, but it defaults to using order 'K',

3365 and will not pass sub-classes through by default.

3366

3367 Examples

3368 --------

3369 >>> x = np.array([[1,2,3],[4,5,6]], order='F')

3370

3371 >>> y = x.copy()

3372

3373 >>> x.fill(0)

3374

3375 >>> x

3376 array([[0, 0, 0],

3377 [0, 0, 0]])

3378

3379 >>> y

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

3381 [4, 5, 6]])

3382

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

3384 True

3385

3386 """))

3387

3388

3389 add_newdoc('numpy.core.multiarray', 'ndarray', ('cumprod',

3390 """

3391 a.cumprod(axis=None, dtype=None, out=None)

3392

3393 Return the cumulative product of the elements along the given axis.

3394

3395 Refer to `numpy.cumprod` for full documentation.

3396

3397 See Also

3398 --------

3399 numpy.cumprod : equivalent function

3400

3401 """))

3402

3403

3404 add_newdoc('numpy.core.multiarray', 'ndarray', ('cumsum',

3405 """

3406 a.cumsum(axis=None, dtype=None, out=None)

3407

3408 Return the cumulative sum of the elements along the given axis.

3409

3410 Refer to `numpy.cumsum` for full documentation.

3411

3412 See Also

3413 --------

3414 numpy.cumsum : equivalent function

3415

3416 """))

3417

3418

3419 add_newdoc('numpy.core.multiarray', 'ndarray', ('diagonal',

3420 """

3421 a.diagonal(offset=0, axis1=0, axis2=1)

3422

3423 Return specified diagonals. In NumPy 1.9 the returned array is a

3424 read-only view instead of a copy as in previous NumPy versions. In

3425 a future version the read-only restriction will be removed.

3426

3427 Refer to :func:`numpy.diagonal` for full documentation.

3428

3429 See Also

3430 --------

3431 numpy.diagonal : equivalent function

3432

3433 """))

3434

3435

3436 add_newdoc('numpy.core.multiarray', 'ndarray', ('dot'))

3437

3438

3439 add_newdoc('numpy.core.multiarray', 'ndarray', ('dump',

3440 """a.dump(file)

3441

3442 Dump a pickle of the array to the specified file.

3443 The array can be read back with pickle.load or numpy.load.

3444

3445 Parameters

3446 ----------

3447 file : str or Path

3448 A string naming the dump file.

3449

3450 .. versionchanged:: 1.17.0

3451 `pathlib.Path` objects are now accepted.

3452

3453 """))

3454

3455

3456 add_newdoc('numpy.core.multiarray', 'ndarray', ('dumps',

3457 """

3458 a.dumps()

3459

3460 Returns the pickle of the array as a string.

3461 pickle.loads will convert the string back to an array.

3462

3463 Parameters

3464 ----------

3465 None

3466

3467 """))

3468

3469

3470 add_newdoc('numpy.core.multiarray', 'ndarray', ('fill',

3471 """

3472 a.fill(value)

3473

3474 Fill the array with a scalar value.

3475

3476 Parameters

3477 ----------

3478 value : scalar

3479 All elements of `a` will be assigned this value.

3480

3481 Examples

3482 --------

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

3484 >>> a.fill(0)

3485 >>> a

3486 array([0, 0])

3487 >>> a = np.empty(2)

3488 >>> a.fill(1)

3489 >>> a

3490 array([1., 1.])

3491

3492 Fill expects a scalar value and always behaves the same as assigning

3493 to a single array element. The following is a rare example where this

3494 distinction is important:

3495

3496 >>> a = np.array([None, None], dtype=object)

3497 >>> a[0] = np.array(3)

3498 >>> a

3499 array([array(3), None], dtype=object)

3500 >>> a.fill(np.array(3))

3501 >>> a

3502 array([array(3), array(3)], dtype=object)

3503

3504 Where other forms of assignments will unpack the array being assigned:

3505

3506 >>> a[...] = np.array(3)

3507 >>> a

3508 array([3, 3], dtype=object)

3509

3510 """))

3511

3512

3513 add_newdoc('numpy.core.multiarray', 'ndarray', ('flatten',

3514 """

3515 a.flatten(order='C')

3516

3517 Return a copy of the array collapsed into one dimension.

3518

3519 Parameters

3520 ----------

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

3522 'C' means to flatten in row-major (C-style) order.

3523 'F' means to flatten in column-major (Fortran-

3524 style) order. 'A' means to flatten in column-major

3525 order if `a` is Fortran *contiguous* in memory,

3526 row-major order otherwise. 'K' means to flatten

3527 `a` in the order the elements occur in memory.

3528 The default is 'C'.

3529

3530 Returns

3531 -------

3532 y : ndarray

3533 A copy of the input array, flattened to one dimension.

3534

3535 See Also

3536 --------

3537 ravel : Return a flattened array.

3538 flat : A 1-D flat iterator over the array.

3539

3540 Examples

3541 --------

3542 >>> a = np.array([[1,2], [3,4]])

3543 >>> a.flatten()

3544 array([1, 2, 3, 4])

3545 >>> a.flatten('F')

3546 array([1, 3, 2, 4])

3547

3548 """))

3549

3550

3551 add_newdoc('numpy.core.multiarray', 'ndarray', ('getfield',

3552 """

3553 a.getfield(dtype, offset=0)

3554

3555 Returns a field of the given array as a certain type.

3556

3557 A field is a view of the array data with a given data-type. The values in

3558 the view are determined by the given type and the offset into the current

3559 array in bytes. The offset needs to be such that the view dtype fits in the

3560 array dtype; for example an array of dtype complex128 has 16-byte elements.

3561 If taking a view with a 32-bit integer (4 bytes), the offset needs to be

3562 between 0 and 12 bytes.

3563

3564 Parameters

3565 ----------

3566 dtype : str or dtype

3567 The data type of the view. The dtype size of the view can not be larger

3568 than that of the array itself.

3569 offset : int

3570 Number of bytes to skip before beginning the element view.

3571

3572 Examples

3573 --------

3574 >>> x = np.diag([1.+1.j]*2)

3575 >>> x[1, 1] = 2 + 4.j

3576 >>> x

3577 array([[1.+1.j, 0.+0.j],

3578 [0.+0.j, 2.+4.j]])

3579 >>> x.getfield(np.float64)

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

3581 [0., 2.]])

3582

3583 By choosing an offset of 8 bytes we can select the complex part of the

3584 array for our view:

3585

3586 >>> x.getfield(np.float64, offset=8)

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

3588 [0., 4.]])

3589

3590 """))

3591

3592

3593 add_newdoc('numpy.core.multiarray', 'ndarray', ('item',

3594 """

3595 a.item(*args)

3596

3597 Copy an element of an array to a standard Python scalar and return it.

3598

3599 Parameters

3600 ----------

3601 \\*args : Arguments (variable number and type)

3602

3603 * none: in this case, the method only works for arrays

3604 with one element (`a.size == 1`), which element is

3605 copied into a standard Python scalar object and returned.

3606

3607 * int_type: this argument is interpreted as a flat index into

3608 the array, specifying which element to copy and return.

3609

3610 * tuple of int_types: functions as does a single int_type argument,

3611 except that the argument is interpreted as an nd-index into the

3612 array.

3613

3614 Returns

3615 -------

3616 z : Standard Python scalar object

3617 A copy of the specified element of the array as a suitable

3618 Python scalar

3619

3620 Notes

3621 -----

3622 When the data type of `a` is longdouble or clongdouble, item() returns

3623 a scalar array object because there is no available Python scalar that

3624 would not lose information. Void arrays return a buffer object for item(),

3625 unless fields are defined, in which case a tuple is returned.

3626

3627 `item` is very similar to a[args], except, instead of an array scalar,

3628 a standard Python scalar is returned. This can be useful for speeding up

3629 access to elements of the array and doing arithmetic on elements of the

3630 array using Python's optimized math.

3631

3632 Examples

3633 --------

3634 >>> np.random.seed(123)

3635 >>> x = np.random.randint(9, size=(3, 3))

3636 >>> x

3637 array([[2, 2, 6],

3638 [1, 3, 6],

3639 [1, 0, 1]])

3640 >>> x.item(3)

3641 1

3642 >>> x.item(7)

3643 0

3644 >>> x.item((0, 1))

3645 2

3646 >>> x.item((2, 2))

3647 1

3648

3649 """))

3650

3651

3652 add_newdoc('numpy.core.multiarray', 'ndarray', ('itemset',

3653 """

3654 a.itemset(*args)

3655

3656 Insert scalar into an array (scalar is cast to array's dtype, if possible)

3657

3658 There must be at least 1 argument, and define the last argument

3659 as *item*. Then, ``a.itemset(*args)`` is equivalent to but faster

3660 than ``a[args] = item``. The item should be a scalar value and `args`

3661 must select a single item in the array `a`.

3662

3663 Parameters

3664 ----------

3665 \\*args : Arguments

3666 If one argument: a scalar, only used in case `a` is of size 1.

3667 If two arguments: the last argument is the value to be set

3668 and must be a scalar, the first argument specifies a single array

3669 element location. It is either an int or a tuple.

3670

3671 Notes

3672 -----

3673 Compared to indexing syntax, `itemset` provides some speed increase

3674 for placing a scalar into a particular location in an `ndarray`,

3675 if you must do this. However, generally this is discouraged:

3676 among other problems, it complicates the appearance of the code.

3677 Also, when using `itemset` (and `item`) inside a loop, be sure

3678 to assign the methods to a local variable to avoid the attribute

3679 look-up at each loop iteration.

3680

3681 Examples

3682 --------

3683 >>> np.random.seed(123)

3684 >>> x = np.random.randint(9, size=(3, 3))

3685 >>> x

3686 array([[2, 2, 6],

3687 [1, 3, 6],

3688 [1, 0, 1]])

3689 >>> x.itemset(4, 0)

3690 >>> x.itemset((2, 2), 9)

3691 >>> x

3692 array([[2, 2, 6],

3693 [1, 0, 6],

3694 [1, 0, 9]])

3695

3696 """))

3697

3698

3699 add_newdoc('numpy.core.multiarray', 'ndarray', ('max',

3700 """

3701 a.max(axis=None, out=None, keepdims=False, initial=<no value>, where=True)

3702

3703 Return the maximum along a given axis.

3704

3705 Refer to `numpy.amax` for full documentation.

3706

3707 See Also

3708 --------

3709 numpy.amax : equivalent function

3710

3711 """))

3712

3713

3714 add_newdoc('numpy.core.multiarray', 'ndarray', ('mean',

3715 """

3716 a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)

3717

3718 Returns the average of the array elements along given axis.

3719

3720 Refer to `numpy.mean` for full documentation.

3721

3722 See Also

3723 --------

3724 numpy.mean : equivalent function

3725

3726 """))

3727

3728

3729 add_newdoc('numpy.core.multiarray', 'ndarray', ('min',

3730 """

3731 a.min(axis=None, out=None, keepdims=False, initial=<no value>, where=True)

3732

3733 Return the minimum along a given axis.

3734

3735 Refer to `numpy.amin` for full documentation.

3736

3737 See Also

3738 --------

3739 numpy.amin : equivalent function

3740

3741 """))

3742

3743

3744 add_newdoc('numpy.core.multiarray', 'ndarray', ('newbyteorder',

3745 """

3746 arr.newbyteorder(new_order='S', /)

3747

3748 Return the array with the same data viewed with a different byte order.

3749

3750 Equivalent to::

3751

3752 arr.view(arr.dtype.newbytorder(new_order))

3753

3754 Changes are also made in all fields and sub-arrays of the array data

3755 type.

3756

3757

3758

3759 Parameters

3760 ----------

3761 new_order : string, optional

3762 Byte order to force; a value from the byte order specifications

3763 below. `new_order` codes can be any of:

3764

3765 * 'S' - swap dtype from current to opposite endian

3766 * {'<', 'little'} - little endian

3767 * {'>', 'big'} - big endian

3768 * {'=', 'native'} - native order, equivalent to `sys.byteorder`

3769 * {'|', 'I'} - ignore (no change to byte order)

3770

3771 The default value ('S') results in swapping the current

3772 byte order.

3773

3774

3775 Returns

3776 -------

3777 new_arr : array

3778 New array object with the dtype reflecting given change to the

3779 byte order.

3780

3781 """))

3782

3783

3784 add_newdoc('numpy.core.multiarray', 'ndarray', ('nonzero',

3785 """

3786 a.nonzero()

3787

3788 Return the indices of the elements that are non-zero.

3789

3790 Refer to `numpy.nonzero` for full documentation.

3791

3792 See Also

3793 --------

3794 numpy.nonzero : equivalent function

3795

3796 """))

3797

3798

3799 add_newdoc('numpy.core.multiarray', 'ndarray', ('prod',

3800 """

3801 a.prod(axis=None, dtype=None, out=None, keepdims=False, initial=1, where=True)

3802

3803 Return the product of the array elements over the given axis

3804

3805 Refer to `numpy.prod` for full documentation.

3806

3807 See Also

3808 --------

3809 numpy.prod : equivalent function

3810

3811 """))

3812

3813

3814 add_newdoc('numpy.core.multiarray', 'ndarray', ('ptp',

3815 """

3816 a.ptp(axis=None, out=None, keepdims=False)

3817

3818 Peak to peak (maximum - minimum) value along a given axis.

3819

3820 Refer to `numpy.ptp` for full documentation.

3821

3822 See Also

3823 --------

3824 numpy.ptp : equivalent function

3825

3826 """))

3827

3828

3829 add_newdoc('numpy.core.multiarray', 'ndarray', ('put',

3830 """

3831 a.put(indices, values, mode='raise')

3832

3833 Set ``a.flat[n] = values[n]`` for all `n` in indices.

3834

3835 Refer to `numpy.put` for full documentation.

3836

3837 See Also

3838 --------

3839 numpy.put : equivalent function

3840

3841 """))

3842

3843

3844 add_newdoc('numpy.core.multiarray', 'ndarray', ('ravel',

3845 """

3846 a.ravel([order])

3847

3848 Return a flattened array.

3849

3850 Refer to `numpy.ravel` for full documentation.

3851

3852 See Also

3853 --------

3854 numpy.ravel : equivalent function

3855

3856 ndarray.flat : a flat iterator on the array.

3857

3858 """))

3859

3860

3861 add_newdoc('numpy.core.multiarray', 'ndarray', ('repeat',

3862 """

3863 a.repeat(repeats, axis=None)

3864

3865 Repeat elements of an array.

3866

3867 Refer to `numpy.repeat` for full documentation.

3868

3869 See Also

3870 --------

3871 numpy.repeat : equivalent function

3872

3873 """))

3874

3875

3876 add_newdoc('numpy.core.multiarray', 'ndarray', ('reshape',

3877 """

3878 a.reshape(shape, order='C')

3879

3880 Returns an array containing the same data with a new shape.

3881

3882 Refer to `numpy.reshape` for full documentation.

3883

3884 See Also

3885 --------

3886 numpy.reshape : equivalent function

3887

3888 Notes

3889 -----

3890 Unlike the free function `numpy.reshape`, this method on `ndarray` allows

3891 the elements of the shape parameter to be passed in as separate arguments.

3892 For example, ``a.reshape(10, 11)`` is equivalent to

3893 ``a.reshape((10, 11))``.

3894

3895 """))

3896

3897

3898 add_newdoc('numpy.core.multiarray', 'ndarray', ('resize',

3899 """

3900 a.resize(new_shape, refcheck=True)

3901

3902 Change shape and size of array in-place.

3903

3904 Parameters

3905 ----------

3906 new_shape : tuple of ints, or `n` ints

3907 Shape of resized array.

3908 refcheck : bool, optional

3909 If False, reference count will not be checked. Default is True.

3910

3911 Returns

3912 -------

3913 None

3914

3915 Raises

3916 ------

3917 ValueError

3918 If `a` does not own its own data or references or views to it exist,

3919 and the data memory must be changed.

3920 PyPy only: will always raise if the data memory must be changed, since

3921 there is no reliable way to determine if references or views to it

3922 exist.

3923

3924 SystemError

3925 If the `order` keyword argument is specified. This behaviour is a

3926 bug in NumPy.

3927

3928 See Also

3929 --------

3930 resize : Return a new array with the specified shape.

3931

3932 Notes

3933 -----

3934 This reallocates space for the data area if necessary.

3935

3936 Only contiguous arrays (data elements consecutive in memory) can be

3937 resized.

3938

3939 The purpose of the reference count check is to make sure you

3940 do not use this array as a buffer for another Python object and then

3941 reallocate the memory. However, reference counts can increase in

3942 other ways so if you are sure that you have not shared the memory

3943 for this array with another Python object, then you may safely set

3944 `refcheck` to False.

3945

3946 Examples

3947 --------

3948 Shrinking an array: array is flattened (in the order that the data are

3949 stored in memory), resized, and reshaped:

3950

3951 >>> a = np.array([[0, 1], [2, 3]], order='C')

3952 >>> a.resize((2, 1))

3953 >>> a

3954 array([[0],

3955 [1]])

3956

3957 >>> a = np.array([[0, 1], [2, 3]], order='F')

3958 >>> a.resize((2, 1))

3959 >>> a

3960 array([[0],

3961 [2]])

3962

3963 Enlarging an array: as above, but missing entries are filled with zeros:

3964

3965 >>> b = np.array([[0, 1], [2, 3]])

3966 >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple

3967 >>> b

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

3969 [3, 0, 0]])

3970

3971 Referencing an array prevents resizing...

3972

3973 >>> c = a

3974 >>> a.resize((1, 1))

3975 Traceback (most recent call last):

3976 ...

3977 ValueError: cannot resize an array that references or is referenced ...

3978

3979 Unless `refcheck` is False:

3980

3981 >>> a.resize((1, 1), refcheck=False)

3982 >>> a

3983 array([[0]])

3984 >>> c

3985 array([[0]])

3986

3987 """))

3988

3989

3990 add_newdoc('numpy.core.multiarray', 'ndarray', ('round',

3991 """

3992 a.round(decimals=0, out=None)

3993

3994 Return `a` with each element rounded to the given number of decimals.

3995

3996 Refer to `numpy.around` for full documentation.

3997

3998 See Also

3999 --------

4000 numpy.around : equivalent function

4001

4002 """))

4003

4004

4005 add_newdoc('numpy.core.multiarray', 'ndarray', ('searchsorted',

4006 """

4007 a.searchsorted(v, side='left', sorter=None)

4008

4009 Find indices where elements of v should be inserted in a to maintain order.

4010

4011 For full documentation, see `numpy.searchsorted`

4012

4013 See Also

4014 --------

4015 numpy.searchsorted : equivalent function

4016

4017 """))

4018

4019

4020 add_newdoc('numpy.core.multiarray', 'ndarray', ('setfield',

4021 """

4022 a.setfield(val, dtype, offset=0)

4023

4024 Put a value into a specified place in a field defined by a data-type.

4025

4026 Place `val` into `a`'s field defined by `dtype` and beginning `offset`

4027 bytes into the field.

4028

4029 Parameters

4030 ----------

4031 val : object

4032 Value to be placed in field.

4033 dtype : dtype object

4034 Data-type of the field in which to place `val`.

4035 offset : int, optional

4036 The number of bytes into the field at which to place `val`.

4037

4038 Returns

4039 -------

4040 None

4041

4042 See Also

4043 --------

4044 getfield

4045

4046 Examples

4047 --------

4048 >>> x = np.eye(3)

4049 >>> x.getfield(np.float64)

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

4051 [0., 1., 0.],

4052 [0., 0., 1.]])

4053 >>> x.setfield(3, np.int32)

4054 >>> x.getfield(np.int32)

4055 array([[3, 3, 3],

4056 [3, 3, 3],

4057 [3, 3, 3]], dtype=int32)

4058 >>> x

4059 array([[1.0e+000, 1.5e-323, 1.5e-323],

4060 [1.5e-323, 1.0e+000, 1.5e-323],

4061 [1.5e-323, 1.5e-323, 1.0e+000]])

4062 >>> x.setfield(np.eye(3), np.int32)

4063 >>> x

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

4065 [0., 1., 0.],

4066 [0., 0., 1.]])

4067

4068 """))

4069

4070

4071 add_newdoc('numpy.core.multiarray', 'ndarray', ('setflags',

4072 """

4073 a.setflags(write=None, align=None, uic=None)

4074

4075 Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY,

4076 respectively.

4077

4078 These Boolean-valued flags affect how numpy interprets the memory

4079 area used by `a` (see Notes below). The ALIGNED flag can only

4080 be set to True if the data is actually aligned according to the type.

4081 The WRITEBACKIFCOPY and flag can never be set

4082 to True. The flag WRITEABLE can only be set to True if the array owns its

4083 own memory, or the ultimate owner of the memory exposes a writeable buffer

4084 interface, or is a string. (The exception for string is made so that

4085 unpickling can be done without copying memory.)

4086

4087 Parameters

4088 ----------

4089 write : bool, optional

4090 Describes whether or not `a` can be written to.

4091 align : bool, optional

4092 Describes whether or not `a` is aligned properly for its type.

4093 uic : bool, optional

4094 Describes whether or not `a` is a copy of another "base" array.

4095

4096 Notes

4097 -----

4098 Array flags provide information about how the memory area used

4099 for the array is to be interpreted. There are 7 Boolean flags

4100 in use, only four of which can be changed by the user:

4101 WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.

4102

4103 WRITEABLE (W) the data area can be written to;

4104

4105 ALIGNED (A) the data and strides are aligned appropriately for the hardware

4106 (as determined by the compiler);

4107

4108 WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced

4109 by .base). When the C-API function PyArray_ResolveWritebackIfCopy is

4110 called, the base array will be updated with the contents of this array.

4111

4112 All flags can be accessed using the single (upper case) letter as well

4113 as the full name.

4114

4115 Examples

4116 --------

4117 >>> y = np.array([[3, 1, 7],

4118 ... [2, 0, 0],

4119 ... [8, 5, 9]])

4120 >>> y

4121 array([[3, 1, 7],

4122 [2, 0, 0],

4123 [8, 5, 9]])

4124 >>> y.flags

4125 C_CONTIGUOUS : True

4126 F_CONTIGUOUS : False

4127 OWNDATA : True

4128 WRITEABLE : True

4129 ALIGNED : True

4130 WRITEBACKIFCOPY : False

4131 >>> y.setflags(write=0, align=0)

4132 >>> y.flags

4133 C_CONTIGUOUS : True

4134 F_CONTIGUOUS : False

4135 OWNDATA : True

4136 WRITEABLE : False

4137 ALIGNED : False

4138 WRITEBACKIFCOPY : False

4139 >>> y.setflags(uic=1)

4140 Traceback (most recent call last):

4141 File "<stdin>", line 1, in <module>

4142 ValueError: cannot set WRITEBACKIFCOPY flag to True

4143

4144 """))

4145

4146

4147 add_newdoc('numpy.core.multiarray', 'ndarray', ('sort',

4148 """

4149 a.sort(axis=-1, kind=None, order=None)

4150

4151 Sort an array in-place. Refer to `numpy.sort` for full documentation.

4152

4153 Parameters

4154 ----------

4155 axis : int, optional

4156 Axis along which to sort. Default is -1, which means sort along the

4157 last axis.

4158 kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional

4159 Sorting algorithm. The default is 'quicksort'. Note that both 'stable'

4160 and 'mergesort' use timsort under the covers and, in general, the

4161 actual implementation will vary with datatype. The 'mergesort' option

4162 is retained for backwards compatibility.

4163

4164 .. versionchanged:: 1.15.0

4165 The 'stable' option was added.

4166

4167 order : str or list of str, optional

4168 When `a` is an array with fields defined, this argument specifies

4169 which fields to compare first, second, etc. A single field can

4170 be specified as a string, and not all fields need be specified,

4171 but unspecified fields will still be used, in the order in which

4172 they come up in the dtype, to break ties.

4173

4174 See Also

4175 --------

4176 numpy.sort : Return a sorted copy of an array.

4177 numpy.argsort : Indirect sort.

4178 numpy.lexsort : Indirect stable sort on multiple keys.

4179 numpy.searchsorted : Find elements in sorted array.

4180 numpy.partition: Partial sort.

4181

4182 Notes

4183 -----

4184 See `numpy.sort` for notes on the different sorting algorithms.

4185

4186 Examples

4187 --------

4188 >>> a = np.array([[1,4], [3,1]])

4189 >>> a.sort(axis=1)

4190 >>> a

4191 array([[1, 4],

4192 [1, 3]])

4193 >>> a.sort(axis=0)

4194 >>> a

4195 array([[1, 3],

4196 [1, 4]])

4197

4198 Use the `order` keyword to specify a field to use when sorting a

4199 structured array:

4200

4201 >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])

4202 >>> a.sort(order='y')

4203 >>> a

4204 array([(b'c', 1), (b'a', 2)],

4205 dtype=[('x', 'S1'), ('y', '<i8')])

4206

4207 """))

4208

4209

4210 add_newdoc('numpy.core.multiarray', 'ndarray', ('partition',

4211 """

4212 a.partition(kth, axis=-1, kind='introselect', order=None)

4213

4214 Rearranges the elements in the array in such a way that the value of the

4215 element in kth position is in the position it would be in a sorted array.

4216 All elements smaller than the kth element are moved before this element and

4217 all equal or greater are moved behind it. The ordering of the elements in

4218 the two partitions is undefined.

4219

4220 .. versionadded:: 1.8.0

4221

4222 Parameters

4223 ----------

4224 kth : int or sequence of ints

4225 Element index to partition by. The kth element value will be in its

4226 final sorted position and all smaller elements will be moved before it

4227 and all equal or greater elements behind it.

4228 The order of all elements in the partitions is undefined.

4229 If provided with a sequence of kth it will partition all elements

4230 indexed by kth of them into their sorted position at once.

4231

4232 .. deprecated:: 1.22.0

4233 Passing booleans as index is deprecated.

4234 axis : int, optional

4235 Axis along which to sort. Default is -1, which means sort along the

4236 last axis.

4237 kind : {'introselect'}, optional

4238 Selection algorithm. Default is 'introselect'.

4239 order : str or list of str, optional

4240 When `a` is an array with fields defined, this argument specifies

4241 which fields to compare first, second, etc. A single field can

4242 be specified as a string, and not all fields need to be specified,

4243 but unspecified fields will still be used, in the order in which

4244 they come up in the dtype, to break ties.

4245

4246 See Also

4247 --------

4248 numpy.partition : Return a partitioned copy of an array.

4249 argpartition : Indirect partition.

4250 sort : Full sort.

4251

4252 Notes

4253 -----

4254 See ``np.partition`` for notes on the different algorithms.

4255

4256 Examples

4257 --------

4258 >>> a = np.array([3, 4, 2, 1])

4259 >>> a.partition(3)

4260 >>> a

4261 array([2, 1, 3, 4])

4262

4263 >>> a.partition((1, 3))

4264 >>> a

4265 array([1, 2, 3, 4])

4266 """))

4267

4268

4269 add_newdoc('numpy.core.multiarray', 'ndarray', ('squeeze',

4270 """

4271 a.squeeze(axis=None)

4272

4273 Remove axes of length one from `a`.

4274

4275 Refer to `numpy.squeeze` for full documentation.

4276

4277 See Also

4278 --------

4279 numpy.squeeze : equivalent function

4280

4281 """))

4282

4283

4284 add_newdoc('numpy.core.multiarray', 'ndarray', ('std',

4285 """

4286 a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)

4287

4288 Returns the standard deviation of the array elements along given axis.

4289

4290 Refer to `numpy.std` for full documentation.

4291

4292 See Also

4293 --------

4294 numpy.std : equivalent function

4295

4296 """))

4297

4298

4299 add_newdoc('numpy.core.multiarray', 'ndarray', ('sum',

4300 """

4301 a.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)

4302

4303 Return the sum of the array elements over the given axis.

4304

4305 Refer to `numpy.sum` for full documentation.

4306

4307 See Also

4308 --------

4309 numpy.sum : equivalent function

4310

4311 """))

4312

4313

4314 add_newdoc('numpy.core.multiarray', 'ndarray', ('swapaxes',

4315 """

4316 a.swapaxes(axis1, axis2)

4317

4318 Return a view of the array with `axis1` and `axis2` interchanged.

4319

4320 Refer to `numpy.swapaxes` for full documentation.

4321

4322 See Also

4323 --------

4324 numpy.swapaxes : equivalent function

4325

4326 """))

4327

4328

4329 add_newdoc('numpy.core.multiarray', 'ndarray', ('take',

4330 """

4331 a.take(indices, axis=None, out=None, mode='raise')

4332

4333 Return an array formed from the elements of `a` at the given indices.

4334

4335 Refer to `numpy.take` for full documentation.

4336

4337 See Also

4338 --------

4339 numpy.take : equivalent function

4340

4341 """))

4342

4343

4344 add_newdoc('numpy.core.multiarray', 'ndarray', ('tofile',

4345 """

4346 a.tofile(fid, sep="", format="%s")

4347

4348 Write array to a file as text or binary (default).

4349

4350 Data is always written in 'C' order, independent of the order of `a`.

4351 The data produced by this method can be recovered using the function

4352 fromfile().

4353

4354 Parameters

4355 ----------

4356 fid : file or str or Path

4357 An open file object, or a string containing a filename.

4358

4359 .. versionchanged:: 1.17.0

4360 `pathlib.Path` objects are now accepted.

4361

4362 sep : str

4363 Separator between array items for text output.

4364 If "" (empty), a binary file is written, equivalent to

4365 ``file.write(a.tobytes())``.

4366 format : str

4367 Format string for text file output.

4368 Each entry in the array is formatted to text by first converting

4369 it to the closest Python type, and then using "format" % item.

4370

4371 Notes

4372 -----

4373 This is a convenience function for quick storage of array data.

4374 Information on endianness and precision is lost, so this method is not a

4375 good choice for files intended to archive data or transport data between

4376 machines with different endianness. Some of these problems can be overcome

4377 by outputting the data as text files, at the expense of speed and file

4378 size.

4379

4380 When fid is a file object, array contents are directly written to the

4381 file, bypassing the file object's ``write`` method. As a result, tofile

4382 cannot be used with files objects supporting compression (e.g., GzipFile)

4383 or file-like objects that do not support ``fileno()`` (e.g., BytesIO).

4384

4385 """))

4386

4387

4388 add_newdoc('numpy.core.multiarray', 'ndarray', ('tolist',

4389 """

4390 a.tolist()

4391

4392 Return the array as an ``a.ndim``-levels deep nested list of Python scalars.

4393

4394 Return a copy of the array data as a (nested) Python list.

4395 Data items are converted to the nearest compatible builtin Python type, via

4396 the `~numpy.ndarray.item` function.

4397

4398 If ``a.ndim`` is 0, then since the depth of the nested list is 0, it will

4399 not be a list at all, but a simple Python scalar.

4400

4401 Parameters

4402 ----------

4403 none

4404

4405 Returns

4406 -------

4407 y : object, or list of object, or list of list of object, or ...

4408 The possibly nested list of array elements.

4409

4410 Notes

4411 -----

4412 The array may be recreated via ``a = np.array(a.tolist())``, although this

4413 may sometimes lose precision.

4414

4415 Examples

4416 --------

4417 For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``,

4418 except that ``tolist`` changes numpy scalars to Python scalars:

4419

4420 >>> a = np.uint32([1, 2])

4421 >>> a_list = list(a)

4422 >>> a_list

4423 [1, 2]

4424 >>> type(a_list[0])

4425 <class 'numpy.uint32'>

4426 >>> a_tolist = a.tolist()

4427 >>> a_tolist

4428 [1, 2]

4429 >>> type(a_tolist[0])

4430 <class 'int'>

4431

4432 Additionally, for a 2D array, ``tolist`` applies recursively:

4433

4434 >>> a = np.array([[1, 2], [3, 4]])

4435 >>> list(a)

4436 [array([1, 2]), array([3, 4])]

4437 >>> a.tolist()

4438 [[1, 2], [3, 4]]

4439

4440 The base case for this recursion is a 0D array:

4441

4442 >>> a = np.array(1)

4443 >>> list(a)

4444 Traceback (most recent call last):

4445 ...

4446 TypeError: iteration over a 0-d array

4447 >>> a.tolist()

4448 1

4449 """))

4450

4451

4452 add_newdoc('numpy.core.multiarray', 'ndarray', ('tobytes', """

4453 a.tobytes(order='C')

4454

4455 Construct Python bytes containing the raw data bytes in the array.

4456

4457 Constructs Python bytes showing a copy of the raw contents of

4458 data memory. The bytes object is produced in C-order by default.

4459 This behavior is controlled by the ``order`` parameter.

4460

4461 .. versionadded:: 1.9.0

4462

4463 Parameters

4464 ----------

4465 order : {'C', 'F', 'A'}, optional

4466 Controls the memory layout of the bytes object. 'C' means C-order,

4467 'F' means F-order, 'A' (short for *Any*) means 'F' if `a` is

4468 Fortran contiguous, 'C' otherwise. Default is 'C'.

4469

4470 Returns

4471 -------

4472 s : bytes

4473 Python bytes exhibiting a copy of `a`'s raw data.

4474

4475 See also

4476 --------

4477 frombuffer

4478 Inverse of this operation, construct a 1-dimensional array from Python

4479 bytes.

4480

4481 Examples

4482 --------

4483 >>> x = np.array([[0, 1], [2, 3]], dtype='<u2')

4484 >>> x.tobytes()

4485 b'\\x00\\x00\\x01\\x00\\x02\\x00\\x03\\x00'

4486 >>> x.tobytes('C') == x.tobytes()

4487 True

4488 >>> x.tobytes('F')

4489 b'\\x00\\x00\\x02\\x00\\x01\\x00\\x03\\x00'

4490

4491 """))

4492

4493

4494 add_newdoc('numpy.core.multiarray', 'ndarray', ('tostring', r"""

4495 a.tostring(order='C')

4496

4497 A compatibility alias for `tobytes`, with exactly the same behavior.

4498

4499 Despite its name, it returns `bytes` not `str`\ s.

4500

4501 .. deprecated:: 1.19.0

4502 """))

4503

4504

4505 add_newdoc('numpy.core.multiarray', 'ndarray', ('trace',

4506 """

4507 a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)

4508

4509 Return the sum along diagonals of the array.

4510

4511 Refer to `numpy.trace` for full documentation.

4512

4513 See Also

4514 --------

4515 numpy.trace : equivalent function

4516

4517 """))

4518

4519

4520 add_newdoc('numpy.core.multiarray', 'ndarray', ('transpose',

4521 """

4522 a.transpose(*axes)

4523

4524 Returns a view of the array with axes transposed.

4525

4526 Refer to `numpy.transpose` for full documentation.

4527

4528 Parameters

4529 ----------

4530 axes : None, tuple of ints, or `n` ints

4531

4532 * None or no argument: reverses the order of the axes.

4533

4534 * tuple of ints: `i` in the `j`-th place in the tuple means that the

4535 array's `i`-th axis becomes the transposed array's `j`-th axis.

4536

4537 * `n` ints: same as an n-tuple of the same ints (this form is

4538 intended simply as a "convenience" alternative to the tuple form).

4539

4540 Returns

4541 -------

4542 p : ndarray

4543 View of the array with its axes suitably permuted.

4544

4545 See Also

4546 --------

4547 transpose : Equivalent function.

4548 ndarray.T : Array property returning the array transposed.

4549 ndarray.reshape : Give a new shape to an array without changing its data.

4550

4551 Examples

4552 --------

4553 >>> a = np.array([[1, 2], [3, 4]])

4554 >>> a

4555 array([[1, 2],

4556 [3, 4]])

4557 >>> a.transpose()

4558 array([[1, 3],

4559 [2, 4]])

4560 >>> a.transpose((1, 0))

4561 array([[1, 3],

4562 [2, 4]])

4563 >>> a.transpose(1, 0)

4564 array([[1, 3],

4565 [2, 4]])

4566

4567 >>> a = np.array([1, 2, 3, 4])

4568 >>> a

4569 array([1, 2, 3, 4])

4570 >>> a.transpose()

4571 array([1, 2, 3, 4])

4572

4573 """))

4574

4575

4576 add_newdoc('numpy.core.multiarray', 'ndarray', ('var',

4577 """

4578 a.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)

4579

4580 Returns the variance of the array elements, along given axis.

4581

4582 Refer to `numpy.var` for full documentation.

4583

4584 See Also

4585 --------

4586 numpy.var : equivalent function

4587

4588 """))

4589

4590

4591 add_newdoc('numpy.core.multiarray', 'ndarray', ('view',

4592 """

4593 a.view([dtype][, type])

4594

4595 New view of array with the same data.

4596

4597 .. note::

4598 Passing None for ``dtype`` is different from omitting the parameter,

4599 since the former invokes ``dtype(None)`` which is an alias for

4600 ``dtype('float_')``.

4601

4602 Parameters

4603 ----------

4604 dtype : data-type or ndarray sub-class, optional

4605 Data-type descriptor of the returned view, e.g., float32 or int16.

4606 Omitting it results in the view having the same data-type as `a`.

4607 This argument can also be specified as an ndarray sub-class, which

4608 then specifies the type of the returned object (this is equivalent to

4609 setting the ``type`` parameter).

4610 type : Python type, optional

4611 Type of the returned view, e.g., ndarray or matrix. Again, omission

4612 of the parameter results in type preservation.

4613

4614 Notes

4615 -----

4616 ``a.view()`` is used two different ways:

4617

4618 ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view

4619 of the array's memory with a different data-type. This can cause a

4620 reinterpretation of the bytes of memory.

4621

4622 ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just

4623 returns an instance of `ndarray_subclass` that looks at the same array

4624 (same shape, dtype, etc.) This does not cause a reinterpretation of the

4625 memory.

4626

4627 For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of

4628 bytes per entry than the previous dtype (for example, converting a regular

4629 array to a structured array), then the last axis of ``a`` must be

4630 contiguous. This axis will be resized in the result.

4631

4632 .. versionchanged:: 1.23.0

4633 Only the last axis needs to be contiguous. Previously, the entire array

4634 had to be C-contiguous.

4635

4636 Examples

4637 --------

4638 >>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)])

4639

4640 Viewing array data using a different type and dtype:

4641

4642 >>> y = x.view(dtype=np.int16, type=np.matrix)

4643 >>> y

4644 matrix([[513]], dtype=int16)

4645 >>> print(type(y))

4646 <class 'numpy.matrix'>

4647

4648 Creating a view on a structured array so it can be used in calculations

4649

4650 >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)])

4651 >>> xv = x.view(dtype=np.int8).reshape(-1,2)

4652 >>> xv

4653 array([[1, 2],

4654 [3, 4]], dtype=int8)

4655 >>> xv.mean(0)

4656 array([2., 3.])

4657

4658 Making changes to the view changes the underlying array

4659

4660 >>> xv[0,1] = 20

4661 >>> x

4662 array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])

4663

4664 Using a view to convert an array to a recarray:

4665

4666 >>> z = x.view(np.recarray)

4667 >>> z.a

4668 array([1, 3], dtype=int8)

4669

4670 Views share data:

4671

4672 >>> x[0] = (9, 10)

4673 >>> z[0]

4674 (9, 10)

4675

4676 Views that change the dtype size (bytes per entry) should normally be

4677 avoided on arrays defined by slices, transposes, fortran-ordering, etc.:

4678

4679 >>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16)

4680 >>> y = x[:, ::2]

4681 >>> y

4682 array([[1, 3],

4683 [4, 6]], dtype=int16)

4684 >>> y.view(dtype=[('width', np.int16), ('length', np.int16)])

4685 Traceback (most recent call last):

4686 ...

4687 ValueError: To change to a dtype of a different size, the last axis must be contiguous

4688 >>> z = y.copy()

4689 >>> z.view(dtype=[('width', np.int16), ('length', np.int16)])

4690 array([[(1, 3)],

4691 [(4, 6)]], dtype=[('width', '<i2'), ('length', '<i2')])

4692

4693 However, views that change dtype are totally fine for arrays with a

4694 contiguous last axis, even if the rest of the axes are not C-contiguous:

4695

4696 >>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4)

4697 >>> x.transpose(1, 0, 2).view(np.int16)

4698 array([[[ 256, 770],

4699 [3340, 3854]],

4700 <BLANKLINE>

4701 [[1284, 1798],

4702 [4368, 4882]],

4703 <BLANKLINE>

4704 [[2312, 2826],

4705 [5396, 5910]]], dtype=int16)

4706

4707 """))

4708

4709

4710##############################################################################

4711#

4712# umath functions

4713#

4714##############################################################################

4715

4716 add_newdoc('numpy.core.umath', 'frompyfunc',

4717 """

4718 frompyfunc(func, /, nin, nout, *[, identity])

4719

4720 Takes an arbitrary Python function and returns a NumPy ufunc.

4721

4722 Can be used, for example, to add broadcasting to a built-in Python

4723 function (see Examples section).

4724

4725 Parameters

4726 ----------

4727 func : Python function object

4728 An arbitrary Python function.

4729 nin : int

4730 The number of input arguments.

4731 nout : int

4732 The number of objects returned by `func`.

4733 identity : object, optional

4734 The value to use for the `~numpy.ufunc.identity` attribute of the resulting

4735 object. If specified, this is equivalent to setting the underlying

4736 C ``identity`` field to ``PyUFunc_IdentityValue``.

4737 If omitted, the identity is set to ``PyUFunc_None``. Note that this is

4738 _not_ equivalent to setting the identity to ``None``, which implies the

4739 operation is reorderable.

4740

4741 Returns

4742 -------

4743 out : ufunc

4744 Returns a NumPy universal function (``ufunc``) object.

4745

4746 See Also

4747 --------

4748 vectorize : Evaluates pyfunc over input arrays using broadcasting rules of numpy.

4749

4750 Notes

4751 -----

4752 The returned ufunc always returns PyObject arrays.

4753

4754 Examples

4755 --------

4756 Use frompyfunc to add broadcasting to the Python function ``oct``:

4757

4758 >>> oct_array = np.frompyfunc(oct, 1, 1)

4759 >>> oct_array(np.array((10, 30, 100)))

4760 array(['0o12', '0o36', '0o144'], dtype=object)

4761 >>> np.array((oct(10), oct(30), oct(100))) # for comparison

4762 array(['0o12', '0o36', '0o144'], dtype='<U5')

4763

4764 """)

4765

4766 add_newdoc('numpy.core.umath', 'geterrobj',

4767 """

4768 geterrobj()

4769

4770 Return the current object that defines floating-point error handling.

4771

4772 The error object contains all information that defines the error handling

4773 behavior in NumPy. `geterrobj` is used internally by the other

4774 functions that get and set error handling behavior (`geterr`, `seterr`,

4775 `geterrcall`, `seterrcall`).

4776

4777 Returns

4778 -------

4779 errobj : list

4780 The error object, a list containing three elements:

4781 [internal numpy buffer size, error mask, error callback function].

4782

4783 The error mask is a single integer that holds the treatment information

4784 on all four floating point errors. The information for each error type

4785 is contained in three bits of the integer. If we print it in base 8, we

4786 can see what treatment is set for "invalid", "under", "over", and

4787 "divide" (in that order). The printed string can be interpreted with

4788

4789 * 0 : 'ignore'

4790 * 1 : 'warn'

4791 * 2 : 'raise'

4792 * 3 : 'call'

4793 * 4 : 'print'

4794 * 5 : 'log'

4795

4796 See Also

4797 --------

4798 seterrobj, seterr, geterr, seterrcall, geterrcall

4799 getbufsize, setbufsize

4800

4801 Notes

4802 -----

4803 For complete documentation of the types of floating-point exceptions and

4804 treatment options, see `seterr`.

4805

4806 Examples

4807 --------

4808 >>> np.geterrobj() # first get the defaults

4809 [8192, 521, None]

4810

4811 >>> def err_handler(type, flag):

4812 ... print("Floating point error (%s), with flag %s" % (type, flag))

4813 ...

4814 >>> old_bufsize = np.setbufsize(20000)

4815 >>> old_err = np.seterr(divide='raise')

4816 >>> old_handler = np.seterrcall(err_handler)

4817 >>> np.geterrobj()

4818 [8192, 521, <function err_handler at 0x91dcaac>]

4819

4820 >>> old_err = np.seterr(all='ignore')

4821 >>> np.base_repr(np.geterrobj()[1], 8)

4822 '0'

4823 >>> old_err = np.seterr(divide='warn', over='log', under='call',

4824 ... invalid='print')

4825 >>> np.base_repr(np.geterrobj()[1], 8)

4826 '4351'

4827

4828 """)

4829

4830 add_newdoc('numpy.core.umath', 'seterrobj',

4831 """

4832 seterrobj(errobj, /)

4833

4834 Set the object that defines floating-point error handling.

4835

4836 The error object contains all information that defines the error handling

4837 behavior in NumPy. `seterrobj` is used internally by the other

4838 functions that set error handling behavior (`seterr`, `seterrcall`).

4839

4840 Parameters

4841 ----------

4842 errobj : list

4843 The error object, a list containing three elements:

4844 [internal numpy buffer size, error mask, error callback function].

4845

4846 The error mask is a single integer that holds the treatment information

4847 on all four floating point errors. The information for each error type

4848 is contained in three bits of the integer. If we print it in base 8, we

4849 can see what treatment is set for "invalid", "under", "over", and

4850 "divide" (in that order). The printed string can be interpreted with

4851

4852 * 0 : 'ignore'

4853 * 1 : 'warn'

4854 * 2 : 'raise'

4855 * 3 : 'call'

4856 * 4 : 'print'

4857 * 5 : 'log'

4858

4859 See Also

4860 --------

4861 geterrobj, seterr, geterr, seterrcall, geterrcall

4862 getbufsize, setbufsize

4863

4864 Notes

4865 -----

4866 For complete documentation of the types of floating-point exceptions and

4867 treatment options, see `seterr`.

4868

4869 Examples

4870 --------

4871 >>> old_errobj = np.geterrobj() # first get the defaults

4872 >>> old_errobj

4873 [8192, 521, None]

4874

4875 >>> def err_handler(type, flag):

4876 ... print("Floating point error (%s), with flag %s" % (type, flag))

4877 ...

4878 >>> new_errobj = [20000, 12, err_handler]

4879 >>> np.seterrobj(new_errobj)

4880 >>> np.base_repr(12, 8) # int for divide=4 ('print') and over=1 ('warn')

4881 '14'

4882 >>> np.geterr()

4883 {'over': 'warn', 'divide': 'print', 'invalid': 'ignore', 'under': 'ignore'}

4884 >>> np.geterrcall() is err_handler

4885 True

4886

4887 """)

4888

4889

4890##############################################################################

4891#

4892# compiled_base functions

4893#

4894##############################################################################

4895

4896 add_newdoc('numpy.core.multiarray', 'add_docstring',

4897 """

4898 add_docstring(obj, docstring)

4899

4900 Add a docstring to a built-in obj if possible.

4901 If the obj already has a docstring raise a RuntimeError

4902 If this routine does not know how to add a docstring to the object

4903 raise a TypeError

4904 """)

4905

4906 add_newdoc('numpy.core.umath', '_add_newdoc_ufunc',

4907 """

4908 add_ufunc_docstring(ufunc, new_docstring)

4909

4910 Replace the docstring for a ufunc with new_docstring.

4911 This method will only work if the current docstring for

4912 the ufunc is NULL. (At the C level, i.e. when ufunc->doc is NULL.)

4913

4914 Parameters

4915 ----------

4916 ufunc : numpy.ufunc

4917 A ufunc whose current doc is NULL.

4918 new_docstring : string

4919 The new docstring for the ufunc.

4920

4921 Notes

4922 -----

4923 This method allocates memory for new_docstring on

4924 the heap. Technically this creates a mempory leak, since this

4925 memory will not be reclaimed until the end of the program

4926 even if the ufunc itself is removed. However this will only

4927 be a problem if the user is repeatedly creating ufuncs with

4928 no documentation, adding documentation via add_newdoc_ufunc,

4929 and then throwing away the ufunc.

4930 """)

4931

4932 add_newdoc('numpy.core.multiarray', 'get_handler_name',

4933 """

4934 get_handler_name(a: ndarray) -> str,None

4935

4936 Return the name of the memory handler used by `a`. If not provided, return

4937 the name of the memory handler that will be used to allocate data for the

4938 next `ndarray` in this context. May return None if `a` does not own its

4939 memory, in which case you can traverse ``a.base`` for a memory handler.

4940 """)

4941

4942 add_newdoc('numpy.core.multiarray', 'get_handler_version',

4943 """

4944 get_handler_version(a: ndarray) -> int,None

4945

4946 Return the version of the memory handler used by `a`. If not provided,

4947 return the version of the memory handler that will be used to allocate data

4948 for the next `ndarray` in this context. May return None if `a` does not own

4949 its memory, in which case you can traverse ``a.base`` for a memory handler.

4950 """)

4951

4952 add_newdoc('numpy.core.multiarray', '_get_madvise_hugepage',

4953 """

4954 _get_madvise_hugepage() -> bool

4955

4956 Get use of ``madvise (2)`` MADV_HUGEPAGE support when

4957 allocating the array data. Returns the currently set value.

4958 See `global_state` for more information.

4959 """)

4960

4961 add_newdoc('numpy.core.multiarray', '_set_madvise_hugepage',

4962 """

4963 _set_madvise_hugepage(enabled: bool) -> bool

4964

4965 Set or unset use of ``madvise (2)`` MADV_HUGEPAGE support when

4966 allocating the array data. Returns the previously set value.

4967 See `global_state` for more information.

4968 """)

4969

4970 add_newdoc('numpy.core._multiarray_tests', 'format_float_OSprintf_g',

4971 """

4972 format_float_OSprintf_g(val, precision)

4973

4974 Print a floating point scalar using the system's printf function,

4975 equivalent to:

4976

4977 printf("%.*g", precision, val);

4978

4979 for half/float/double, or replacing 'g' by 'Lg' for longdouble. This

4980 method is designed to help cross-validate the format_float_* methods.

4981

4982 Parameters

4983 ----------

4984 val : python float or numpy floating scalar

4985 Value to format.

4986

4987 precision : non-negative integer, optional

4988 Precision given to printf.

4989

4990 Returns

4991 -------

4992 rep : string

4993 The string representation of the floating point value

4994

4995 See Also

4996 --------

4997 format_float_scientific

4998 format_float_positional

4999 """)

5000

5001

5002##############################################################################

5003#

5004# Documentation for ufunc attributes and methods

5005#

5006##############################################################################

5007

5008

5009##############################################################################

5010#

5011# ufunc object

5012#

5013##############################################################################

5014

5015 add_newdoc('numpy.core', 'ufunc',

5016 """

5017 Functions that operate element by element on whole arrays.

5018

5019 To see the documentation for a specific ufunc, use `info`. For

5020 example, ``np.info(np.sin)``. Because ufuncs are written in C

5021 (for speed) and linked into Python with NumPy's ufunc facility,

5022 Python's help() function finds this page whenever help() is called

5023 on a ufunc.

5024

5025 A detailed explanation of ufuncs can be found in the docs for :ref:`ufuncs`.

5026

5027 **Calling ufuncs:** ``op(*x[, out], where=True, **kwargs)``

5028

5029 Apply `op` to the arguments `*x` elementwise, broadcasting the arguments.

5030

5031 The broadcasting rules are:

5032

5033 * Dimensions of length 1 may be prepended to either array.

5034 * Arrays may be repeated along dimensions of length 1.

5035

5036 Parameters

5037 ----------

5038 *x : array_like

5039 Input arrays.

5040 out : ndarray, None, or tuple of ndarray and None, optional

5041 Alternate array object(s) in which to put the result; if provided, it

5042 must have a shape that the inputs broadcast to. A tuple of arrays

5043 (possible only as a keyword argument) must have length equal to the

5044 number of outputs; use None for uninitialized outputs to be

5045 allocated by the ufunc.

5046 where : array_like, optional

5047 This condition is broadcast over the input. At locations where the

5048 condition is True, the `out` array will be set to the ufunc result.

5049 Elsewhere, the `out` array will retain its original value.

5050 Note that if an uninitialized `out` array is created via the default

5051 ``out=None``, locations within it where the condition is False will

5052 remain uninitialized.

5053 **kwargs

5054 For other keyword-only arguments, see the :ref:`ufunc docs <ufuncs.kwargs>`.

5055

5056 Returns

5057 -------

5058 r : ndarray or tuple of ndarray

5059 `r` will have the shape that the arrays in `x` broadcast to; if `out` is

5060 provided, it will be returned. If not, `r` will be allocated and

5061 may contain uninitialized values. If the function has more than one

5062 output, then the result will be a tuple of arrays.

5063

5064 """)

5065

5066

5067##############################################################################

5068#

5069# ufunc attributes

5070#

5071##############################################################################

5072

5073 add_newdoc('numpy.core', 'ufunc', ('identity',

5074 """

5075 The identity value.

5076

5077 Data attribute containing the identity element for the ufunc, if it has one.

5078 If it does not, the attribute value is None.

5079

5080 Examples

5081 --------

5082 >>> np.add.identity

5083 0

5084 >>> np.multiply.identity

5085 1

5086 >>> np.power.identity

5087 1

5088 >>> print(np.exp.identity)

5089 None

5090 """))

5091

5092 add_newdoc('numpy.core', 'ufunc', ('nargs',

5093 """

5094 The number of arguments.

5095

5096 Data attribute containing the number of arguments the ufunc takes, including

5097 optional ones.

5098

5099 Notes

5100 -----

5101 Typically this value will be one more than what you might expect because all

5102 ufuncs take the optional "out" argument.

5103

5104 Examples

5105 --------

5106 >>> np.add.nargs

5107 3

5108 >>> np.multiply.nargs

5109 3

5110 >>> np.power.nargs

5111 3

5112 >>> np.exp.nargs

5113 2

5114 """))

5115

5116 add_newdoc('numpy.core', 'ufunc', ('nin',

5117 """

5118 The number of inputs.

5119

5120 Data attribute containing the number of arguments the ufunc treats as input.

5121

5122 Examples

5123 --------

5124 >>> np.add.nin

5125 2

5126 >>> np.multiply.nin

5127 2

5128 >>> np.power.nin

5129 2

5130 >>> np.exp.nin

5131 1

5132 """))

5133

5134 add_newdoc('numpy.core', 'ufunc', ('nout',

5135 """

5136 The number of outputs.

5137

5138 Data attribute containing the number of arguments the ufunc treats as output.

5139

5140 Notes

5141 -----

5142 Since all ufuncs can take output arguments, this will always be (at least) 1.

5143

5144 Examples

5145 --------

5146 >>> np.add.nout

5147 1

5148 >>> np.multiply.nout

5149 1

5150 >>> np.power.nout

5151 1

5152 >>> np.exp.nout

5153 1

5154

5155 """))

5156

5157 add_newdoc('numpy.core', 'ufunc', ('ntypes',

5158 """

5159 The number of types.

5160

5161 The number of numerical NumPy types - of which there are 18 total - on which

5162 the ufunc can operate.

5163

5164 See Also

5165 --------

5166 numpy.ufunc.types

5167

5168 Examples

5169 --------

5170 >>> np.add.ntypes

5171 18

5172 >>> np.multiply.ntypes

5173 18

5174 >>> np.power.ntypes

5175 17

5176 >>> np.exp.ntypes

5177 7

5178 >>> np.remainder.ntypes

5179 14

5180

5181 """))

5182

5183 add_newdoc('numpy.core', 'ufunc', ('types',

5184 """

5185 Returns a list with types grouped input->output.

5186

5187 Data attribute listing the data-type "Domain-Range" groupings the ufunc can

5188 deliver. The data-types are given using the character codes.

5189

5190 See Also

5191 --------

5192 numpy.ufunc.ntypes

5193

5194 Examples

5195 --------

5196 >>> np.add.types

5197 ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l',

5198 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D',

5199 'GG->G', 'OO->O']

5200

5201 >>> np.multiply.types

5202 ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l',

5203 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D',

5204 'GG->G', 'OO->O']

5205

5206 >>> np.power.types

5207 ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L',

5208 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G',

5209 'OO->O']

5210

5211 >>> np.exp.types

5212 ['f->f', 'd->d', 'g->g', 'F->F', 'D->D', 'G->G', 'O->O']

5213

5214 >>> np.remainder.types

5215 ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L',

5216 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'OO->O']

5217

5218 """))

5219

5220 add_newdoc('numpy.core', 'ufunc', ('signature',

5221 """

5222 Definition of the core elements a generalized ufunc operates on.

5223

5224 The signature determines how the dimensions of each input/output array

5225 are split into core and loop dimensions:

5226

5227 1. Each dimension in the signature is matched to a dimension of the

5228 corresponding passed-in array, starting from the end of the shape tuple.

5229 2. Core dimensions assigned to the same label in the signature must have

5230 exactly matching sizes, no broadcasting is performed.

5231 3. The core dimensions are removed from all inputs and the remaining

5232 dimensions are broadcast together, defining the loop dimensions.

5233

5234 Notes

5235 -----

5236 Generalized ufuncs are used internally in many linalg functions, and in

5237 the testing suite; the examples below are taken from these.

5238 For ufuncs that operate on scalars, the signature is None, which is

5239 equivalent to '()' for every argument.

5240

5241 Examples

5242 --------

5243 >>> np.core.umath_tests.matrix_multiply.signature

5244 '(m,n),(n,p)->(m,p)'

5245 >>> np.linalg._umath_linalg.det.signature

5246 '(m,m)->()'

5247 >>> np.add.signature is None

5248 True # equivalent to '(),()->()'

5249 """))

5250

5251##############################################################################

5252#

5253# ufunc methods

5254#

5255##############################################################################

5256

5257 add_newdoc('numpy.core', 'ufunc', ('reduce',

5258 """

5259 reduce(array, axis=0, dtype=None, out=None, keepdims=False, initial=<no value>, where=True)

5260

5261 Reduces `array`'s dimension by one, by applying ufunc along one axis.

5262

5263 Let :math:`array.shape = (N_0, ..., N_i, ..., N_{M-1})`. Then

5264 :math:`ufunc.reduce(array, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}]` =

5265 the result of iterating `j` over :math:`range(N_i)`, cumulatively applying

5266 ufunc to each :math:`array[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]`.

5267 For a one-dimensional array, reduce produces results equivalent to:

5268 ::

5269

5270 r = op.identity # op = ufunc

5271 for i in range(len(A)):

5272 r = op(r, A[i])

5273 return r

5274

5275 For example, add.reduce() is equivalent to sum().

5276

5277 Parameters

5278 ----------

5279 array : array_like

5280 The array to act on.

5281 axis : None or int or tuple of ints, optional

5282 Axis or axes along which a reduction is performed.

5283 The default (`axis` = 0) is perform a reduction over the first

5284 dimension of the input array. `axis` may be negative, in

5285 which case it counts from the last to the first axis.

5286

5287 .. versionadded:: 1.7.0

5288

5289 If this is None, a reduction is performed over all the axes.

5290 If this is a tuple of ints, a reduction is performed on multiple

5291 axes, instead of a single axis or all the axes as before.

5292

5293 For operations which are either not commutative or not associative,

5294 doing a reduction over multiple axes is not well-defined. The

5295 ufuncs do not currently raise an exception in this case, but will

5296 likely do so in the future.

5297 dtype : data-type code, optional

5298 The type used to represent the intermediate results. Defaults

5299 to the data-type of the output array if this is provided, or

5300 the data-type of the input array if no output array is provided.

5301 out : ndarray, None, or tuple of ndarray and None, optional

5302 A location into which the result is stored. If not provided or None,

5303 a freshly-allocated array is returned. For consistency with

5304 ``ufunc.__call__``, if given as a keyword, this may be wrapped in a

5305 1-element tuple.

5306

5307 .. versionchanged:: 1.13.0

5308 Tuples are allowed for keyword argument.

5309 keepdims : bool, optional

5310 If this is set to True, the axes which are reduced are left

5311 in the result as dimensions with size one. With this option,

5312 the result will broadcast correctly against the original `array`.

5313

5314 .. versionadded:: 1.7.0

5315 initial : scalar, optional

5316 The value with which to start the reduction.

5317 If the ufunc has no identity or the dtype is object, this defaults

5318 to None - otherwise it defaults to ufunc.identity.

5319 If ``None`` is given, the first element of the reduction is used,

5320 and an error is thrown if the reduction is empty.

5321

5322 .. versionadded:: 1.15.0

5323

5324 where : array_like of bool, optional

5325 A boolean array which is broadcasted to match the dimensions

5326 of `array`, and selects elements to include in the reduction. Note

5327 that for ufuncs like ``minimum`` that do not have an identity

5328 defined, one has to pass in also ``initial``.

5329

5330 .. versionadded:: 1.17.0

5331

5332 Returns

5333 -------

5334 r : ndarray

5335 The reduced array. If `out` was supplied, `r` is a reference to it.

5336

5337 Examples

5338 --------

5339 >>> np.multiply.reduce([2,3,5])

5340 30

5341

5342 A multi-dimensional array example:

5343

5344 >>> X = np.arange(8).reshape((2,2,2))

5345 >>> X

5346 array([[[0, 1],

5347 [2, 3]],

5348 [[4, 5],

5349 [6, 7]]])

5350 >>> np.add.reduce(X, 0)

5351 array([[ 4, 6],

5352 [ 8, 10]])

5353 >>> np.add.reduce(X) # confirm: default axis value is 0

5354 array([[ 4, 6],

5355 [ 8, 10]])

5356 >>> np.add.reduce(X, 1)

5357 array([[ 2, 4],

5358 [10, 12]])

5359 >>> np.add.reduce(X, 2)

5360 array([[ 1, 5],

5361 [ 9, 13]])

5362

5363 You can use the ``initial`` keyword argument to initialize the reduction

5364 with a different value, and ``where`` to select specific elements to include:

5365

5366 >>> np.add.reduce([10], initial=5)

5367 15

5368 >>> np.add.reduce(np.ones((2, 2, 2)), axis=(0, 2), initial=10)

5369 array([14., 14.])

5370 >>> a = np.array([10., np.nan, 10])

5371 >>> np.add.reduce(a, where=~np.isnan(a))

5372 20.0

5373

5374 Allows reductions of empty arrays where they would normally fail, i.e.

5375 for ufuncs without an identity.

5376

5377 >>> np.minimum.reduce([], initial=np.inf)

5378 inf

5379 >>> np.minimum.reduce([[1., 2.], [3., 4.]], initial=10., where=[True, False])

5380 array([ 1., 10.])

5381 >>> np.minimum.reduce([])

5382 Traceback (most recent call last):

5383 ...

5384 ValueError: zero-size array to reduction operation minimum which has no identity

5385 """))

5386

5387 add_newdoc('numpy.core', 'ufunc', ('accumulate',

5388 """

5389 accumulate(array, axis=0, dtype=None, out=None)

5390

5391 Accumulate the result of applying the operator to all elements.

5392

5393 For a one-dimensional array, accumulate produces results equivalent to::

5394

5395 r = np.empty(len(A))

5396 t = op.identity # op = the ufunc being applied to A's elements

5397 for i in range(len(A)):

5398 t = op(t, A[i])

5399 r[i] = t

5400 return r

5401

5402 For example, add.accumulate() is equivalent to np.cumsum().

5403

5404 For a multi-dimensional array, accumulate is applied along only one

5405 axis (axis zero by default; see Examples below) so repeated use is

5406 necessary if one wants to accumulate over multiple axes.

5407

5408 Parameters

5409 ----------

5410 array : array_like

5411 The array to act on.

5412 axis : int, optional

5413 The axis along which to apply the accumulation; default is zero.

5414 dtype : data-type code, optional

5415 The data-type used to represent the intermediate results. Defaults

5416 to the data-type of the output array if such is provided, or the

5417 data-type of the input array if no output array is provided.

5418 out : ndarray, None, or tuple of ndarray and None, optional

5419 A location into which the result is stored. If not provided or None,

5420 a freshly-allocated array is returned. For consistency with

5421 ``ufunc.__call__``, if given as a keyword, this may be wrapped in a

5422 1-element tuple.

5423

5424 .. versionchanged:: 1.13.0

5425 Tuples are allowed for keyword argument.

5426

5427 Returns

5428 -------

5429 r : ndarray

5430 The accumulated values. If `out` was supplied, `r` is a reference to

5431 `out`.

5432

5433 Examples

5434 --------

5435 1-D array examples:

5436

5437 >>> np.add.accumulate([2, 3, 5])

5438 array([ 2, 5, 10])

5439 >>> np.multiply.accumulate([2, 3, 5])

5440 array([ 2, 6, 30])

5441

5442 2-D array examples:

5443

5444 >>> I = np.eye(2)

5445 >>> I

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

5447 [0., 1.]])

5448

5449 Accumulate along axis 0 (rows), down columns:

5450

5451 >>> np.add.accumulate(I, 0)

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

5453 [1., 1.]])

5454 >>> np.add.accumulate(I) # no axis specified = axis zero

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

5456 [1., 1.]])

5457

5458 Accumulate along axis 1 (columns), through rows:

5459

5460 >>> np.add.accumulate(I, 1)

5461 array([[1., 1.],

5462 [0., 1.]])

5463

5464 """))

5465

5466 add_newdoc('numpy.core', 'ufunc', ('reduceat',

5467 """

5468 reduceat(array, indices, axis=0, dtype=None, out=None)

5469

5470 Performs a (local) reduce with specified slices over a single axis.

5471

5472 For i in ``range(len(indices))``, `reduceat` computes

5473 ``ufunc.reduce(array[indices[i]:indices[i+1]])``, which becomes the i-th

5474 generalized "row" parallel to `axis` in the final result (i.e., in a

5475 2-D array, for example, if `axis = 0`, it becomes the i-th row, but if

5476 `axis = 1`, it becomes the i-th column). There are three exceptions to this:

5477

5478 * when ``i = len(indices) - 1`` (so for the last index),

5479 ``indices[i+1] = array.shape[axis]``.

5480 * if ``indices[i] >= indices[i + 1]``, the i-th generalized "row" is

5481 simply ``array[indices[i]]``.

5482 * if ``indices[i] >= len(array)`` or ``indices[i] < 0``, an error is raised.

5483

5484 The shape of the output depends on the size of `indices`, and may be

5485 larger than `array` (this happens if ``len(indices) > array.shape[axis]``).

5486

5487 Parameters

5488 ----------

5489 array : array_like

5490 The array to act on.

5491 indices : array_like

5492 Paired indices, comma separated (not colon), specifying slices to

5493 reduce.

5494 axis : int, optional

5495 The axis along which to apply the reduceat.

5496 dtype : data-type code, optional

5497 The type used to represent the intermediate results. Defaults

5498 to the data type of the output array if this is provided, or

5499 the data type of the input array if no output array is provided.

5500 out : ndarray, None, or tuple of ndarray and None, optional

5501 A location into which the result is stored. If not provided or None,

5502 a freshly-allocated array is returned. For consistency with

5503 ``ufunc.__call__``, if given as a keyword, this may be wrapped in a

5504 1-element tuple.

5505

5506 .. versionchanged:: 1.13.0

5507 Tuples are allowed for keyword argument.

5508

5509 Returns

5510 -------

5511 r : ndarray

5512 The reduced values. If `out` was supplied, `r` is a reference to

5513 `out`.

5514

5515 Notes

5516 -----

5517 A descriptive example:

5518

5519 If `array` is 1-D, the function `ufunc.accumulate(array)` is the same as

5520 ``ufunc.reduceat(array, indices)[::2]`` where `indices` is

5521 ``range(len(array) - 1)`` with a zero placed

5522 in every other element:

5523 ``indices = zeros(2 * len(array) - 1)``,

5524 ``indices[1::2] = range(1, len(array))``.

5525

5526 Don't be fooled by this attribute's name: `reduceat(array)` is not

5527 necessarily smaller than `array`.

5528

5529 Examples

5530 --------

5531 To take the running sum of four successive values:

5532

5533 >>> np.add.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2]

5534 array([ 6, 10, 14, 18])

5535

5536 A 2-D example:

5537

5538 >>> x = np.linspace(0, 15, 16).reshape(4,4)

5539 >>> x

5540 array([[ 0., 1., 2., 3.],

5541 [ 4., 5., 6., 7.],

5542 [ 8., 9., 10., 11.],

5543 [12., 13., 14., 15.]])

5544

5545 ::

5546

5547 # reduce such that the result has the following five rows:

5548 # [row1 + row2 + row3]

5549 # [row4]

5550 # [row2]

5551 # [row3]

5552 # [row1 + row2 + row3 + row4]

5553

5554 >>> np.add.reduceat(x, [0, 3, 1, 2, 0])

5555 array([[12., 15., 18., 21.],

5556 [12., 13., 14., 15.],

5557 [ 4., 5., 6., 7.],

5558 [ 8., 9., 10., 11.],

5559 [24., 28., 32., 36.]])

5560

5561 ::

5562

5563 # reduce such that result has the following two columns:

5564 # [col1 * col2 * col3, col4]

5565

5566 >>> np.multiply.reduceat(x, [0, 3], 1)

5567 array([[ 0., 3.],

5568 [ 120., 7.],

5569 [ 720., 11.],

5570 [2184., 15.]])

5571

5572 """))

5573

5574 add_newdoc('numpy.core', 'ufunc', ('outer',

5575 r"""

5576 outer(A, B, /, **kwargs)

5577

5578 Apply the ufunc `op` to all pairs (a, b) with a in `A` and b in `B`.

5579

5580 Let ``M = A.ndim``, ``N = B.ndim``. Then the result, `C`, of

5581 ``op.outer(A, B)`` is an array of dimension M + N such that:

5582

5583 .. math:: C[i_0, ..., i_{M-1}, j_0, ..., j_{N-1}] =

5584 op(A[i_0, ..., i_{M-1}], B[j_0, ..., j_{N-1}])

5585

5586 For `A` and `B` one-dimensional, this is equivalent to::

5587

5588 r = empty(len(A),len(B))

5589 for i in range(len(A)):

5590 for j in range(len(B)):

5591 r[i,j] = op(A[i], B[j]) # op = ufunc in question

5592

5593 Parameters

5594 ----------

5595 A : array_like

5596 First array

5597 B : array_like

5598 Second array

5599 kwargs : any

5600 Arguments to pass on to the ufunc. Typically `dtype` or `out`.

5601 See `ufunc` for a comprehensive overview of all available arguments.

5602

5603 Returns

5604 -------

5605 r : ndarray

5606 Output array

5607

5608 See Also

5609 --------

5610 numpy.outer : A less powerful version of ``np.multiply.outer``

5611 that `ravel`\ s all inputs to 1D. This exists

5612 primarily for compatibility with old code.

5613

5614 tensordot : ``np.tensordot(a, b, axes=((), ()))`` and

5615 ``np.multiply.outer(a, b)`` behave same for all

5616 dimensions of a and b.

5617

5618 Examples

5619 --------

5620 >>> np.multiply.outer([1, 2, 3], [4, 5, 6])

5621 array([[ 4, 5, 6],

5622 [ 8, 10, 12],

5623 [12, 15, 18]])

5624

5625 A multi-dimensional example:

5626

5627 >>> A = np.array([[1, 2, 3], [4, 5, 6]])

5628 >>> A.shape

5629 (2, 3)

5630 >>> B = np.array([[1, 2, 3, 4]])

5631 >>> B.shape

5632 (1, 4)

5633 >>> C = np.multiply.outer(A, B)

5634 >>> C.shape; C

5635 (2, 3, 1, 4)

5636 array([[[[ 1, 2, 3, 4]],

5637 [[ 2, 4, 6, 8]],

5638 [[ 3, 6, 9, 12]]],

5639 [[[ 4, 8, 12, 16]],

5640 [[ 5, 10, 15, 20]],

5641 [[ 6, 12, 18, 24]]]])

5642

5643 """))

5644

5645 add_newdoc('numpy.core', 'ufunc', ('at',

5646 """

5647 at(a, indices, b=None, /)

5648

5649 Performs unbuffered in place operation on operand 'a' for elements

5650 specified by 'indices'. For addition ufunc, this method is equivalent to

5651 ``a[indices] += b``, except that results are accumulated for elements that

5652 are indexed more than once. For example, ``a[[0,0]] += 1`` will only

5653 increment the first element once because of buffering, whereas

5654 ``add.at(a, [0,0], 1)`` will increment the first element twice.

5655

5656 .. versionadded:: 1.8.0

5657

5658 Parameters

5659 ----------

5660 a : array_like

5661 The array to perform in place operation on.

5662 indices : array_like or tuple

5663 Array like index object or slice object for indexing into first

5664 operand. If first operand has multiple dimensions, indices can be a

5665 tuple of array like index objects or slice objects.

5666 b : array_like

5667 Second operand for ufuncs requiring two operands. Operand must be

5668 broadcastable over first operand after indexing or slicing.

5669

5670 Examples

5671 --------

5672 Set items 0 and 1 to their negative values:

5673

5674 >>> a = np.array([1, 2, 3, 4])

5675 >>> np.negative.at(a, [0, 1])

5676 >>> a

5677 array([-1, -2, 3, 4])

5678

5679 Increment items 0 and 1, and increment item 2 twice:

5680

5681 >>> a = np.array([1, 2, 3, 4])

5682 >>> np.add.at(a, [0, 1, 2, 2], 1)

5683 >>> a

5684 array([2, 3, 5, 4])

5685

5686 Add items 0 and 1 in first array to second array,

5687 and store results in first array:

5688

5689 >>> a = np.array([1, 2, 3, 4])

5690 >>> b = np.array([1, 2])

5691 >>> np.add.at(a, [0, 1], b)

5692 >>> a

5693 array([2, 4, 3, 4])

5694

5695 """))

5696

5697 add_newdoc('numpy.core', 'ufunc', ('resolve_dtypes',

5698 """

5699 resolve_dtypes(dtypes, *, signature=None, casting=None, reduction=False)

5700

5701 Find the dtypes NumPy will use for the operation. Both input and

5702 output dtypes are returned and may differ from those provided.

5703

5704 .. note::

5705

5706 This function always applies NEP 50 rules since it is not provided

5707 any actual values. The Python types ``int``, ``float``, and

5708 ``complex`` thus behave weak and should be passed for "untyped"

5709 Python input.

5710

5711 Parameters

5712 ----------

5713 dtypes : tuple of dtypes, None, or literal int, float, complex

5714 The input dtypes for each operand. Output operands can be

5715 None, indicating that the dtype must be found.

5716 signature : tuple of DTypes or None, optional

5717 If given, enforces exact DType (classes) of the specific operand.

5718 The ufunc ``dtype`` argument is equivalent to passing a tuple with

5719 only output dtypes set.

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

5721 The casting mode when casting is necessary. This is identical to

5722 the ufunc call casting modes.

5723 reduction : boolean

5724 If given, the resolution assumes a reduce operation is happening

5725 which slightly changes the promotion and type resolution rules.

5726 `dtypes` is usually something like ``(None, np.dtype("i2"), None)``

5727 for reductions (first input is also the output).

5728

5729 .. note::

5730

5731 The default casting mode is "same_kind", however, as of

5732 NumPy 1.24, NumPy uses "unsafe" for reductions.

5733

5734 Returns

5735 -------

5736 dtypes : tuple of dtypes

5737 The dtypes which NumPy would use for the calculation. Note that

5738 dtypes may not match the passed in ones (casting is necessary).

5739

5740 See Also

5741 --------

5742 numpy.ufunc._resolve_dtypes_and_context :

5743 Similar function to this, but returns additional information which

5744 give access to the core C functionality of NumPy.

5745

5746 Examples

5747 --------

5748 This API requires passing dtypes, define them for convenience:

5749

5750 >>> int32 = np.dtype("int32")

5751 >>> float32 = np.dtype("float32")

5752

5753 The typical ufunc call does not pass an output dtype. `np.add` has two

5754 inputs and one output, so leave the output as ``None`` (not provided):

5755

5756 >>> np.add.resolve_dtypes((int32, float32, None))

5757 (dtype('float64'), dtype('float64'), dtype('float64'))

5758

5759 The loop found uses "float64" for all operands (including the output), the

5760 first input would be cast.

5761

5762 ``resolve_dtypes`` supports "weak" handling for Python scalars by passing

5763 ``int``, ``float``, or ``complex``:

5764

5765 >>> np.add.resolve_dtypes((float32, float, None))

5766 (dtype('float32'), dtype('float32'), dtype('float32'))

5767

5768 Where the Python ``float`` behaves samilar to a Python value ``0.0``

5769 in a ufunc call. (See :ref:`NEP 50 <NEP50>` for details.)

5770

5771 """))

5772

5773 add_newdoc('numpy.core', 'ufunc', ('_resolve_dtypes_and_context',

5774 """

5775 _resolve_dtypes_and_context(dtypes, *, signature=None, casting=None, reduction=False)

5776

5777 See `numpy.ufunc.resolve_dtypes` for parameter information. This

5778 function is considered *unstable*. You may use it, but the returned

5779 information is NumPy version specific and expected to change.

5780 Large API/ABI changes are not expected, but a new NumPy version is

5781 expected to require updating code using this functionality.

5782

5783 This function is designed to be used in conjunction with

5784 `numpy.ufunc._get_strided_loop`. The calls are split to mirror the C API

5785 and allow future improvements.

5786

5787 Returns

5788 -------

5789 dtypes : tuple of dtypes

5790 call_info :

5791 PyCapsule with all necessary information to get access to low level

5792 C calls. See `numpy.ufunc._get_strided_loop` for more information.

5793

5794 """))

5795

5796 add_newdoc('numpy.core', 'ufunc', ('_get_strided_loop',

5797 """

5798 _get_strided_loop(call_info, /, *, fixed_strides=None)

5799

5800 This function fills in the ``call_info`` capsule to include all

5801 information necessary to call the low-level strided loop from NumPy.

5802

5803 See notes for more information.

5804

5805 Parameters

5806 ----------

5807 call_info : PyCapsule

5808 The PyCapsule returned by `numpy.ufunc._resolve_dtypes_and_context`.

5809 fixed_strides : tuple of int or None, optional

5810 A tuple with fixed byte strides of all input arrays. NumPy may use

5811 this information to find specialized loops, so any call must follow

5812 the given stride. Use ``None`` to indicate that the stride is not

5813 known (or not fixed) for all calls.

5814

5815 Notes

5816 -----

5817 Together with `numpy.ufunc._resolve_dtypes_and_context` this function

5818 gives low-level access to the NumPy ufunc loops.

5819 The first function does general preparation and returns the required

5820 information. It returns this as a C capsule with the version specific

5821 name ``numpy_1.24_ufunc_call_info``.

5822 The NumPy 1.24 ufunc call info capsule has the following layout::

5823

5824 typedef struct {

5825 PyArrayMethod_StridedLoop *strided_loop;

5826 PyArrayMethod_Context *context;

5827 NpyAuxData *auxdata;

5828

5829 /* Flag information (expected to change) */

5830 npy_bool requires_pyapi; /* GIL is required by loop */

5831

5832 /* Loop doesn't set FPE flags; if not set check FPE flags */

5833 npy_bool no_floatingpoint_errors;

5834 } ufunc_call_info;

5835

5836 Note that the first call only fills in the ``context``. The call to

5837 ``_get_strided_loop`` fills in all other data.

5838 Please see the ``numpy/experimental_dtype_api.h`` header for exact

5839 call information; the main thing to note is that the new-style loops

5840 return 0 on success, -1 on failure. They are passed context as new

5841 first input and ``auxdata`` as (replaced) last.

5842

5843 Only the ``strided_loop``signature is considered guaranteed stable

5844 for NumPy bug-fix releases. All other API is tied to the experimental

5845 API versioning.

5846

5847 The reason for the split call is that cast information is required to

5848 decide what the fixed-strides will be.

5849

5850 NumPy ties the lifetime of the ``auxdata`` information to the capsule.

5851

5852 """))

5853

5854

5855

5856##############################################################################

5857#

5858# Documentation for dtype attributes and methods

5859#

5860##############################################################################

5861

5862##############################################################################

5863#

5864# dtype object

5865#

5866##############################################################################

5867

5868 add_newdoc('numpy.core.multiarray', 'dtype',

5869 """

5870 dtype(dtype, align=False, copy=False)

5871

5872 Create a data type object.

5873

5874 A numpy array is homogeneous, and contains elements described by a

5875 dtype object. A dtype object can be constructed from different

5876 combinations of fundamental numeric types.

5877

5878 Parameters

5879 ----------

5880 dtype

5881 Object to be converted to a data type object.

5882 align : bool, optional

5883 Add padding to the fields to match what a C compiler would output

5884 for a similar C-struct. Can be ``True`` only if `obj` is a dictionary

5885 or a comma-separated string. If a struct dtype is being created,

5886 this also sets a sticky alignment flag ``isalignedstruct``.

5887 copy : bool, optional

5888 Make a new copy of the data-type object. If ``False``, the result

5889 may just be a reference to a built-in data-type object.

5890

5891 See also

5892 --------

5893 result_type

5894

5895 Examples

5896 --------

5897 Using array-scalar type:

5898

5899 >>> np.dtype(np.int16)

5900 dtype('int16')

5901

5902 Structured type, one field name 'f1', containing int16:

5903

5904 >>> np.dtype([('f1', np.int16)])

5905 dtype([('f1', '<i2')])

5906

5907 Structured type, one field named 'f1', in itself containing a structured

5908 type with one field:

5909

5910 >>> np.dtype([('f1', [('f1', np.int16)])])

5911 dtype([('f1', [('f1', '<i2')])])

5912

5913 Structured type, two fields: the first field contains an unsigned int, the

5914 second an int32:

5915

5916 >>> np.dtype([('f1', np.uint64), ('f2', np.int32)])

5917 dtype([('f1', '<u8'), ('f2', '<i4')])

5918

5919 Using array-protocol type strings:

5920

5921 >>> np.dtype([('a','f8'),('b','S10')])

5922 dtype([('a', '<f8'), ('b', 'S10')])

5923

5924 Using comma-separated field formats. The shape is (2,3):

5925

5926 >>> np.dtype("i4, (2,3)f8")

5927 dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))])

5928

5929 Using tuples. ``int`` is a fixed type, 3 the field's shape. ``void``

5930 is a flexible type, here of size 10:

5931

5932 >>> np.dtype([('hello',(np.int64,3)),('world',np.void,10)])

5933 dtype([('hello', '<i8', (3,)), ('world', 'V10')])

5934

5935 Subdivide ``int16`` into 2 ``int8``'s, called x and y. 0 and 1 are

5936 the offsets in bytes:

5937

5938 >>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)}))

5939 dtype((numpy.int16, [('x', 'i1'), ('y', 'i1')]))

5940

5941 Using dictionaries. Two fields named 'gender' and 'age':

5942

5943 >>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]})

5944 dtype([('gender', 'S1'), ('age', 'u1')])

5945

5946 Offsets in bytes, here 0 and 25:

5947

5948 >>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)})

5949 dtype([('surname', 'S25'), ('age', 'u1')])

5950

5951 """)

5952

5953##############################################################################

5954#

5955# dtype attributes

5956#

5957##############################################################################

5958

5959 add_newdoc('numpy.core.multiarray', 'dtype', ('alignment',

5960 """

5961 The required alignment (bytes) of this data-type according to the compiler.

5962

5963 More information is available in the C-API section of the manual.

5964

5965 Examples

5966 --------

5967

5968 >>> x = np.dtype('i4')

5969 >>> x.alignment

5970 4

5971

5972 >>> x = np.dtype(float)

5973 >>> x.alignment

5974 8

5975

5976 """))

5977

5978 add_newdoc('numpy.core.multiarray', 'dtype', ('byteorder',

5979 """

5980 A character indicating the byte-order of this data-type object.

5981

5982 One of:

5983

5984 === ==============

5985 '=' native

5986 '<' little-endian

5987 '>' big-endian

5988 '|' not applicable

5989 === ==============

5990

5991 All built-in data-type objects have byteorder either '=' or '|'.

5992

5993 Examples

5994 --------

5995

5996 >>> dt = np.dtype('i2')

5997 >>> dt.byteorder

5998 '='

5999 >>> # endian is not relevant for 8 bit numbers

6000 >>> np.dtype('i1').byteorder

6001 '|'

6002 >>> # or ASCII strings

6003 >>> np.dtype('S2').byteorder

6004 '|'

6005 >>> # Even if specific code is given, and it is native

6006 >>> # '=' is the byteorder

6007 >>> import sys

6008 >>> sys_is_le = sys.byteorder == 'little'

6009 >>> native_code = sys_is_le and '<' or '>'

6010 >>> swapped_code = sys_is_le and '>' or '<'

6011 >>> dt = np.dtype(native_code + 'i2')

6012 >>> dt.byteorder

6013 '='

6014 >>> # Swapped code shows up as itself

6015 >>> dt = np.dtype(swapped_code + 'i2')

6016 >>> dt.byteorder == swapped_code

6017 True

6018

6019 """))

6020

6021 add_newdoc('numpy.core.multiarray', 'dtype', ('char',

6022 """A unique character code for each of the 21 different built-in types.

6023

6024 Examples

6025 --------

6026

6027 >>> x = np.dtype(float)

6028 >>> x.char

6029 'd'

6030

6031 """))

6032

6033 add_newdoc('numpy.core.multiarray', 'dtype', ('descr',

6034 """

6035 `__array_interface__` description of the data-type.

6036

6037 The format is that required by the 'descr' key in the

6038 `__array_interface__` attribute.

6039

6040 Warning: This attribute exists specifically for `__array_interface__`,

6041 and passing it directly to `np.dtype` will not accurately reconstruct

6042 some dtypes (e.g., scalar and subarray dtypes).

6043

6044 Examples

6045 --------

6046

6047 >>> x = np.dtype(float)

6048 >>> x.descr

6049 [('', '<f8')]

6050

6051 >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])

6052 >>> dt.descr

6053 [('name', '<U16'), ('grades', '<f8', (2,))]

6054

6055 """))

6056

6057 add_newdoc('numpy.core.multiarray', 'dtype', ('fields',

6058 """

6059 Dictionary of named fields defined for this data type, or ``None``.

6060

6061 The dictionary is indexed by keys that are the names of the fields.

6062 Each entry in the dictionary is a tuple fully describing the field::

6063

6064 (dtype, offset[, title])

6065

6066 Offset is limited to C int, which is signed and usually 32 bits.

6067 If present, the optional title can be any object (if it is a string

6068 or unicode then it will also be a key in the fields dictionary,

6069 otherwise it's meta-data). Notice also that the first two elements

6070 of the tuple can be passed directly as arguments to the ``ndarray.getfield``

6071 and ``ndarray.setfield`` methods.

6072

6073 See Also

6074 --------

6075 ndarray.getfield, ndarray.setfield

6076

6077 Examples

6078 --------

6079 >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])

6080 >>> print(dt.fields)

6081 {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}

6082

6083 """))

6084

6085 add_newdoc('numpy.core.multiarray', 'dtype', ('flags',

6086 """

6087 Bit-flags describing how this data type is to be interpreted.

6088

6089 Bit-masks are in `numpy.core.multiarray` as the constants

6090 `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,

6091 `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation

6092 of these flags is in C-API documentation; they are largely useful

6093 for user-defined data-types.

6094

6095 The following example demonstrates that operations on this particular

6096 dtype requires Python C-API.

6097

6098 Examples

6099 --------

6100

6101 >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])

6102 >>> x.flags

6103 16

6104 >>> np.core.multiarray.NEEDS_PYAPI

6105 16

6106

6107 """))

6108

6109 add_newdoc('numpy.core.multiarray', 'dtype', ('hasobject',

6110 """

6111 Boolean indicating whether this dtype contains any reference-counted

6112 objects in any fields or sub-dtypes.

6113

6114 Recall that what is actually in the ndarray memory representing

6115 the Python object is the memory address of that object (a pointer).

6116 Special handling may be required, and this attribute is useful for

6117 distinguishing data types that may contain arbitrary Python objects

6118 and data-types that won't.

6119

6120 """))

6121

6122 add_newdoc('numpy.core.multiarray', 'dtype', ('isbuiltin',

6123 """

6124 Integer indicating how this dtype relates to the built-in dtypes.

6125

6126 Read-only.

6127

6128 = ========================================================================

6129 0 if this is a structured array type, with fields

6130 1 if this is a dtype compiled into numpy (such as ints, floats etc)

6131 2 if the dtype is for a user-defined numpy type

6132 A user-defined type uses the numpy C-API machinery to extend

6133 numpy to handle a new array type. See

6134 :ref:`user.user-defined-data-types` in the NumPy manual.

6135 = ========================================================================

6136

6137 Examples

6138 --------

6139 >>> dt = np.dtype('i2')

6140 >>> dt.isbuiltin

6141 1

6142 >>> dt = np.dtype('f8')

6143 >>> dt.isbuiltin

6144 1

6145 >>> dt = np.dtype([('field1', 'f8')])

6146 >>> dt.isbuiltin

6147 0

6148

6149 """))

6150

6151 add_newdoc('numpy.core.multiarray', 'dtype', ('isnative',

6152 """

6153 Boolean indicating whether the byte order of this dtype is native

6154 to the platform.

6155

6156 """))

6157

6158 add_newdoc('numpy.core.multiarray', 'dtype', ('isalignedstruct',

6159 """

6160 Boolean indicating whether the dtype is a struct which maintains

6161 field alignment. This flag is sticky, so when combining multiple

6162 structs together, it is preserved and produces new dtypes which

6163 are also aligned.

6164

6165 """))

6166

6167 add_newdoc('numpy.core.multiarray', 'dtype', ('itemsize',

6168 """

6169 The element size of this data-type object.

6170

6171 For 18 of the 21 types this number is fixed by the data-type.

6172 For the flexible data-types, this number can be anything.

6173

6174 Examples

6175 --------

6176

6177 >>> arr = np.array([[1, 2], [3, 4]])

6178 >>> arr.dtype

6179 dtype('int64')

6180 >>> arr.itemsize

6181 8

6182

6183 >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])

6184 >>> dt.itemsize

6185 80

6186

6187 """))

6188

6189 add_newdoc('numpy.core.multiarray', 'dtype', ('kind',

6190 """

6191 A character code (one of 'biufcmMOSUV') identifying the general kind of data.

6192

6193 = ======================

6194 b boolean

6195 i signed integer

6196 u unsigned integer

6197 f floating-point

6198 c complex floating-point

6199 m timedelta

6200 M datetime

6201 O object

6202 S (byte-)string

6203 U Unicode

6204 V void

6205 = ======================

6206

6207 Examples

6208 --------

6209

6210 >>> dt = np.dtype('i4')

6211 >>> dt.kind

6212 'i'

6213 >>> dt = np.dtype('f8')

6214 >>> dt.kind

6215 'f'

6216 >>> dt = np.dtype([('field1', 'f8')])

6217 >>> dt.kind

6218 'V'

6219

6220 """))

6221

6222 add_newdoc('numpy.core.multiarray', 'dtype', ('metadata',

6223 """

6224 Either ``None`` or a readonly dictionary of metadata (mappingproxy).

6225

6226 The metadata field can be set using any dictionary at data-type

6227 creation. NumPy currently has no uniform approach to propagating

6228 metadata; although some array operations preserve it, there is no

6229 guarantee that others will.

6230

6231 .. warning::

6232

6233 Although used in certain projects, this feature was long undocumented

6234 and is not well supported. Some aspects of metadata propagation

6235 are expected to change in the future.

6236

6237 Examples

6238 --------

6239

6240 >>> dt = np.dtype(float, metadata={"key": "value"})

6241 >>> dt.metadata["key"]

6242 'value'

6243 >>> arr = np.array([1, 2, 3], dtype=dt)

6244 >>> arr.dtype.metadata

6245 mappingproxy({'key': 'value'})

6246

6247 Adding arrays with identical datatypes currently preserves the metadata:

6248

6249 >>> (arr + arr).dtype.metadata

6250 mappingproxy({'key': 'value'})

6251

6252 But if the arrays have different dtype metadata, the metadata may be

6253 dropped:

6254

6255 >>> dt2 = np.dtype(float, metadata={"key2": "value2"})

6256 >>> arr2 = np.array([3, 2, 1], dtype=dt2)

6257 >>> (arr + arr2).dtype.metadata is None

6258 True # The metadata field is cleared so None is returned

6259 """))

6260

6261 add_newdoc('numpy.core.multiarray', 'dtype', ('name',

6262 """

6263 A bit-width name for this data-type.

6264

6265 Un-sized flexible data-type objects do not have this attribute.

6266

6267 Examples

6268 --------

6269

6270 >>> x = np.dtype(float)

6271 >>> x.name

6272 'float64'

6273 >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])

6274 >>> x.name

6275 'void640'

6276

6277 """))

6278

6279 add_newdoc('numpy.core.multiarray', 'dtype', ('names',

6280 """

6281 Ordered list of field names, or ``None`` if there are no fields.

6282

6283 The names are ordered according to increasing byte offset. This can be

6284 used, for example, to walk through all of the named fields in offset order.

6285

6286 Examples

6287 --------

6288 >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])

6289 >>> dt.names

6290 ('name', 'grades')

6291

6292 """))

6293

6294 add_newdoc('numpy.core.multiarray', 'dtype', ('num',

6295 """

6296 A unique number for each of the 21 different built-in types.

6297

6298 These are roughly ordered from least-to-most precision.

6299

6300 Examples

6301 --------

6302

6303 >>> dt = np.dtype(str)

6304 >>> dt.num

6305 19

6306

6307 >>> dt = np.dtype(float)

6308 >>> dt.num

6309 12

6310

6311 """))

6312

6313 add_newdoc('numpy.core.multiarray', 'dtype', ('shape',

6314 """

6315 Shape tuple of the sub-array if this data type describes a sub-array,

6316 and ``()`` otherwise.

6317

6318 Examples

6319 --------

6320

6321 >>> dt = np.dtype(('i4', 4))

6322 >>> dt.shape

6323 (4,)

6324

6325 >>> dt = np.dtype(('i4', (2, 3)))

6326 >>> dt.shape

6327 (2, 3)

6328

6329 """))

6330

6331 add_newdoc('numpy.core.multiarray', 'dtype', ('ndim',

6332 """

6333 Number of dimensions of the sub-array if this data type describes a

6334 sub-array, and ``0`` otherwise.

6335

6336 .. versionadded:: 1.13.0

6337

6338 Examples

6339 --------

6340 >>> x = np.dtype(float)

6341 >>> x.ndim

6342 0

6343

6344 >>> x = np.dtype((float, 8))

6345 >>> x.ndim

6346 1

6347

6348 >>> x = np.dtype(('i4', (3, 4)))

6349 >>> x.ndim

6350 2

6351

6352 """))

6353

6354 add_newdoc('numpy.core.multiarray', 'dtype', ('str',

6355 """The array-protocol typestring of this data-type object."""))

6356

6357 add_newdoc('numpy.core.multiarray', 'dtype', ('subdtype',

6358 """

6359 Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and

6360 None otherwise.

6361

6362 The *shape* is the fixed shape of the sub-array described by this

6363 data type, and *item_dtype* the data type of the array.

6364

6365 If a field whose dtype object has this attribute is retrieved,

6366 then the extra dimensions implied by *shape* are tacked on to

6367 the end of the retrieved array.

6368

6369 See Also

6370 --------

6371 dtype.base

6372

6373 Examples

6374 --------

6375 >>> x = numpy.dtype('8f')

6376 >>> x.subdtype

6377 (dtype('float32'), (8,))

6378

6379 >>> x = numpy.dtype('i2')

6380 >>> x.subdtype

6381 >>>

6382

6383 """))

6384

6385 add_newdoc('numpy.core.multiarray', 'dtype', ('base',

6386 """

6387 Returns dtype for the base element of the subarrays,

6388 regardless of their dimension or shape.

6389

6390 See Also

6391 --------

6392 dtype.subdtype

6393

6394 Examples

6395 --------

6396 >>> x = numpy.dtype('8f')

6397 >>> x.base

6398 dtype('float32')

6399

6400 >>> x = numpy.dtype('i2')

6401 >>> x.base

6402 dtype('int16')

6403

6404 """))

6405

6406 add_newdoc('numpy.core.multiarray', 'dtype', ('type',

6407 """The type object used to instantiate a scalar of this data-type."""))

6408

6409##############################################################################

6410#

6411# dtype methods

6412#

6413##############################################################################

6414

6415 add_newdoc('numpy.core.multiarray', 'dtype', ('newbyteorder',

6416 """

6417 newbyteorder(new_order='S', /)

6418

6419 Return a new dtype with a different byte order.

6420

6421 Changes are also made in all fields and sub-arrays of the data type.

6422

6423 Parameters

6424 ----------

6425 new_order : string, optional

6426 Byte order to force; a value from the byte order specifications

6427 below. The default value ('S') results in swapping the current

6428 byte order. `new_order` codes can be any of:

6429

6430 * 'S' - swap dtype from current to opposite endian

6431 * {'<', 'little'} - little endian

6432 * {'>', 'big'} - big endian

6433 * {'=', 'native'} - native order

6434 * {'|', 'I'} - ignore (no change to byte order)

6435

6436 Returns

6437 -------

6438 new_dtype : dtype

6439 New dtype object with the given change to the byte order.

6440

6441 Notes

6442 -----

6443 Changes are also made in all fields and sub-arrays of the data type.

6444

6445 Examples

6446 --------

6447 >>> import sys

6448 >>> sys_is_le = sys.byteorder == 'little'

6449 >>> native_code = sys_is_le and '<' or '>'

6450 >>> swapped_code = sys_is_le and '>' or '<'

6451 >>> native_dt = np.dtype(native_code+'i2')

6452 >>> swapped_dt = np.dtype(swapped_code+'i2')

6453 >>> native_dt.newbyteorder('S') == swapped_dt

6454 True

6455 >>> native_dt.newbyteorder() == swapped_dt

6456 True

6457 >>> native_dt == swapped_dt.newbyteorder('S')

6458 True

6459 >>> native_dt == swapped_dt.newbyteorder('=')

6460 True

6461 >>> native_dt == swapped_dt.newbyteorder('N')

6462 True

6463 >>> native_dt == native_dt.newbyteorder('|')

6464 True

6465 >>> np.dtype('<i2') == native_dt.newbyteorder('<')

6466 True

6467 >>> np.dtype('<i2') == native_dt.newbyteorder('L')

6468 True

6469 >>> np.dtype('>i2') == native_dt.newbyteorder('>')

6470 True

6471 >>> np.dtype('>i2') == native_dt.newbyteorder('B')

6472 True

6473

6474 """))

6475

6476 add_newdoc('numpy.core.multiarray', 'dtype', ('__class_getitem__',

6477 """

6478 __class_getitem__(item, /)

6479

6480 Return a parametrized wrapper around the `~numpy.dtype` type.

6481

6482 .. versionadded:: 1.22

6483

6484 Returns

6485 -------

6486 alias : types.GenericAlias

6487 A parametrized `~numpy.dtype` type.

6488

6489 Examples

6490 --------

6491 >>> import numpy as np

6492

6493 >>> np.dtype[np.int64]

6494 numpy.dtype[numpy.int64]

6495

6496 Notes

6497 -----

6498 This method is only available for python 3.9 and later.

6499

6500 See Also

6501 --------

6502 :pep:`585` : Type hinting generics in standard collections.

6503

6504 """))

6505

6506 add_newdoc('numpy.core.multiarray', 'dtype', ('__ge__',

6507 """

6508 __ge__(value, /)

6509

6510 Return ``self >= value``.

6511

6512 Equivalent to ``np.can_cast(value, self, casting="safe")``.

6513

6514 See Also

6515 --------

6516 can_cast : Returns True if cast between data types can occur according to

6517 the casting rule.

6518

6519 """))

6520

6521 add_newdoc('numpy.core.multiarray', 'dtype', ('__le__',

6522 """

6523 __le__(value, /)

6524

6525 Return ``self <= value``.

6526

6527 Equivalent to ``np.can_cast(self, value, casting="safe")``.

6528

6529 See Also

6530 --------

6531 can_cast : Returns True if cast between data types can occur according to

6532 the casting rule.

6533

6534 """))

6535

6536 add_newdoc('numpy.core.multiarray', 'dtype', ('__gt__',

6537 """

6538 __ge__(value, /)

6539

6540 Return ``self > value``.

6541

6542 Equivalent to

6543 ``self != value and np.can_cast(value, self, casting="safe")``.

6544

6545 See Also

6546 --------

6547 can_cast : Returns True if cast between data types can occur according to

6548 the casting rule.

6549

6550 """))

6551

6552 add_newdoc('numpy.core.multiarray', 'dtype', ('__lt__',

6553 """

6554 __lt__(value, /)

6555

6556 Return ``self < value``.

6557

6558 Equivalent to

6559 ``self != value and np.can_cast(self, value, casting="safe")``.

6560

6561 See Also

6562 --------

6563 can_cast : Returns True if cast between data types can occur according to

6564 the casting rule.

6565

6566 """))

6567

6568##############################################################################

6569#

6570# Datetime-related Methods

6571#

6572##############################################################################

6573

6574 add_newdoc('numpy.core.multiarray', 'busdaycalendar',

6575 """

6576 busdaycalendar(weekmask='1111100', holidays=None)

6577

6578 A business day calendar object that efficiently stores information

6579 defining valid days for the busday family of functions.

6580

6581 The default valid days are Monday through Friday ("business days").

6582 A busdaycalendar object can be specified with any set of weekly

6583 valid days, plus an optional "holiday" dates that always will be invalid.

6584

6585 Once a busdaycalendar object is created, the weekmask and holidays

6586 cannot be modified.

6587

6588 .. versionadded:: 1.7.0

6589

6590 Parameters

6591 ----------

6592 weekmask : str or array_like of bool, optional

6593 A seven-element array indicating which of Monday through Sunday are

6594 valid days. May be specified as a length-seven list or array, like

6595 [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string

6596 like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for

6597 weekdays, optionally separated by white space. Valid abbreviations

6598 are: Mon Tue Wed Thu Fri Sat Sun

6599 holidays : array_like of datetime64[D], optional

6600 An array of dates to consider as invalid dates, no matter which

6601 weekday they fall upon. Holiday dates may be specified in any

6602 order, and NaT (not-a-time) dates are ignored. This list is

6603 saved in a normalized form that is suited for fast calculations

6604 of valid days.

6605

6606 Returns

6607 -------

6608 out : busdaycalendar

6609 A business day calendar object containing the specified

6610 weekmask and holidays values.

6611

6612 See Also

6613 --------

6614 is_busday : Returns a boolean array indicating valid days.

6615 busday_offset : Applies an offset counted in valid days.

6616 busday_count : Counts how many valid days are in a half-open date range.

6617

6618 Attributes

6619 ----------

6620 Note: once a busdaycalendar object is created, you cannot modify the

6621 weekmask or holidays. The attributes return copies of internal data.

6622 weekmask : (copy) seven-element array of bool

6623 holidays : (copy) sorted array of datetime64[D]

6624

6625 Examples

6626 --------

6627 >>> # Some important days in July

6628 ... bdd = np.busdaycalendar(

6629 ... holidays=['2011-07-01', '2011-07-04', '2011-07-17'])

6630 >>> # Default is Monday to Friday weekdays

6631 ... bdd.weekmask

6632 array([ True, True, True, True, True, False, False])

6633 >>> # Any holidays already on the weekend are removed

6634 ... bdd.holidays

6635 array(['2011-07-01', '2011-07-04'], dtype='datetime64[D]')

6636 """)

6637

6638 add_newdoc('numpy.core.multiarray', 'busdaycalendar', ('weekmask',

6639 """A copy of the seven-element boolean mask indicating valid days."""))

6640

6641 add_newdoc('numpy.core.multiarray', 'busdaycalendar', ('holidays',

6642 """A copy of the holiday array indicating additional invalid days."""))

6643

6644 add_newdoc('numpy.core.multiarray', 'normalize_axis_index',

6645 """

6646 normalize_axis_index(axis, ndim, msg_prefix=None)

6647

6648 Normalizes an axis index, `axis`, such that is a valid positive index into

6649 the shape of array with `ndim` dimensions. Raises an AxisError with an

6650 appropriate message if this is not possible.

6651

6652 Used internally by all axis-checking logic.

6653

6654 .. versionadded:: 1.13.0

6655

6656 Parameters

6657 ----------

6658 axis : int

6659 The un-normalized index of the axis. Can be negative

6660 ndim : int

6661 The number of dimensions of the array that `axis` should be normalized

6662 against

6663 msg_prefix : str

6664 A prefix to put before the message, typically the name of the argument

6665

6666 Returns

6667 -------

6668 normalized_axis : int

6669 The normalized axis index, such that `0 <= normalized_axis < ndim`

6670

6671 Raises

6672 ------

6673 AxisError

6674 If the axis index is invalid, when `-ndim <= axis < ndim` is false.

6675

6676 Examples

6677 --------

6678 >>> normalize_axis_index(0, ndim=3)

6679 0

6680 >>> normalize_axis_index(1, ndim=3)

6681 1

6682 >>> normalize_axis_index(-1, ndim=3)

6683 2

6684

6685 >>> normalize_axis_index(3, ndim=3)

6686 Traceback (most recent call last):

6687 ...

6688 AxisError: axis 3 is out of bounds for array of dimension 3

6689 >>> normalize_axis_index(-4, ndim=3, msg_prefix='axes_arg')

6690 Traceback (most recent call last):

6691 ...

6692 AxisError: axes_arg: axis -4 is out of bounds for array of dimension 3

6693 """)

6694

6695 add_newdoc('numpy.core.multiarray', 'datetime_data',

6696 """

6697 datetime_data(dtype, /)

6698

6699 Get information about the step size of a date or time type.

6700

6701 The returned tuple can be passed as the second argument of `numpy.datetime64` and

6702 `numpy.timedelta64`.

6703

6704 Parameters

6705 ----------

6706 dtype : dtype

6707 The dtype object, which must be a `datetime64` or `timedelta64` type.

6708

6709 Returns

6710 -------

6711 unit : str

6712 The :ref:`datetime unit <arrays.dtypes.dateunits>` on which this dtype

6713 is based.

6714 count : int

6715 The number of base units in a step.

6716

6717 Examples

6718 --------

6719 >>> dt_25s = np.dtype('timedelta64[25s]')

6720 >>> np.datetime_data(dt_25s)

6721 ('s', 25)

6722 >>> np.array(10, dt_25s).astype('timedelta64[s]')

6723 array(250, dtype='timedelta64[s]')

6724

6725 The result can be used to construct a datetime that uses the same units

6726 as a timedelta

6727

6728 >>> np.datetime64('2010', np.datetime_data(dt_25s))

6729 numpy.datetime64('2010-01-01T00:00:00','25s')

6730 """)

6731

6732

6733##############################################################################

6734#

6735# Documentation for `generic` attributes and methods

6736#

6737##############################################################################

6738

6739 add_newdoc('numpy.core.numerictypes', 'generic',

6740 """

6741 Base class for numpy scalar types.

6742

6743 Class from which most (all?) numpy scalar types are derived. For

6744 consistency, exposes the same API as `ndarray`, despite many

6745 consequent attributes being either "get-only," or completely irrelevant.

6746 This is the class from which it is strongly suggested users should derive

6747 custom scalar types.

6748

6749 """)

6750

6751# Attributes

6752

6753 def refer_to_array_attribute(attr, method=True):

6754 docstring = """

6755 Scalar {} identical to the corresponding array attribute.

6756

6757 Please see `ndarray.{}`.

6758 """

6759

6760 return attr, docstring.format("method" if method else "attribute", attr)

6761

6762

6763 add_newdoc('numpy.core.numerictypes', 'generic',

6764 refer_to_array_attribute('T', method=False))

6765

6766 add_newdoc('numpy.core.numerictypes', 'generic',

6767 refer_to_array_attribute('base', method=False))

6768

6769 add_newdoc('numpy.core.numerictypes', 'generic', ('data',

6770 """Pointer to start of data."""))

6771

6772 add_newdoc('numpy.core.numerictypes', 'generic', ('dtype',

6773 """Get array data-descriptor."""))

6774

6775 add_newdoc('numpy.core.numerictypes', 'generic', ('flags',

6776 """The integer value of flags."""))

6777

6778 add_newdoc('numpy.core.numerictypes', 'generic', ('flat',

6779 """A 1-D view of the scalar."""))

6780

6781 add_newdoc('numpy.core.numerictypes', 'generic', ('imag',

6782 """The imaginary part of the scalar."""))

6783

6784 add_newdoc('numpy.core.numerictypes', 'generic', ('itemsize',

6785 """The length of one element in bytes."""))

6786

6787 add_newdoc('numpy.core.numerictypes', 'generic', ('nbytes',

6788 """The length of the scalar in bytes."""))

6789

6790 add_newdoc('numpy.core.numerictypes', 'generic', ('ndim',

6791 """The number of array dimensions."""))

6792

6793 add_newdoc('numpy.core.numerictypes', 'generic', ('real',

6794 """The real part of the scalar."""))

6795

6796 add_newdoc('numpy.core.numerictypes', 'generic', ('shape',

6797 """Tuple of array dimensions."""))

6798

6799 add_newdoc('numpy.core.numerictypes', 'generic', ('size',

6800 """The number of elements in the gentype."""))

6801

6802 add_newdoc('numpy.core.numerictypes', 'generic', ('strides',

6803 """Tuple of bytes steps in each dimension."""))

6804

6805# Methods

6806

6807 add_newdoc('numpy.core.numerictypes', 'generic',

6808 refer_to_array_attribute('all'))

6809

6810 add_newdoc('numpy.core.numerictypes', 'generic',

6811 refer_to_array_attribute('any'))

6812

6813 add_newdoc('numpy.core.numerictypes', 'generic',

6814 refer_to_array_attribute('argmax'))

6815

6816 add_newdoc('numpy.core.numerictypes', 'generic',

6817 refer_to_array_attribute('argmin'))

6818

6819 add_newdoc('numpy.core.numerictypes', 'generic',

6820 refer_to_array_attribute('argsort'))

6821

6822 add_newdoc('numpy.core.numerictypes', 'generic',

6823 refer_to_array_attribute('astype'))

6824

6825 add_newdoc('numpy.core.numerictypes', 'generic',

6826 refer_to_array_attribute('byteswap'))

6827

6828 add_newdoc('numpy.core.numerictypes', 'generic',

6829 refer_to_array_attribute('choose'))

6830

6831 add_newdoc('numpy.core.numerictypes', 'generic',

6832 refer_to_array_attribute('clip'))

6833

6834 add_newdoc('numpy.core.numerictypes', 'generic',

6835 refer_to_array_attribute('compress'))

6836

6837 add_newdoc('numpy.core.numerictypes', 'generic',

6838 refer_to_array_attribute('conjugate'))

6839

6840 add_newdoc('numpy.core.numerictypes', 'generic',

6841 refer_to_array_attribute('copy'))

6842

6843 add_newdoc('numpy.core.numerictypes', 'generic',

6844 refer_to_array_attribute('cumprod'))

6845

6846 add_newdoc('numpy.core.numerictypes', 'generic',

6847 refer_to_array_attribute('cumsum'))

6848

6849 add_newdoc('numpy.core.numerictypes', 'generic',

6850 refer_to_array_attribute('diagonal'))

6851

6852 add_newdoc('numpy.core.numerictypes', 'generic',

6853 refer_to_array_attribute('dump'))

6854

6855 add_newdoc('numpy.core.numerictypes', 'generic',

6856 refer_to_array_attribute('dumps'))

6857

6858 add_newdoc('numpy.core.numerictypes', 'generic',

6859 refer_to_array_attribute('fill'))

6860

6861 add_newdoc('numpy.core.numerictypes', 'generic',

6862 refer_to_array_attribute('flatten'))

6863

6864 add_newdoc('numpy.core.numerictypes', 'generic',

6865 refer_to_array_attribute('getfield'))

6866

6867 add_newdoc('numpy.core.numerictypes', 'generic',

6868 refer_to_array_attribute('item'))

6869

6870 add_newdoc('numpy.core.numerictypes', 'generic',

6871 refer_to_array_attribute('itemset'))

6872

6873 add_newdoc('numpy.core.numerictypes', 'generic',

6874 refer_to_array_attribute('max'))

6875

6876 add_newdoc('numpy.core.numerictypes', 'generic',

6877 refer_to_array_attribute('mean'))

6878

6879 add_newdoc('numpy.core.numerictypes', 'generic',

6880 refer_to_array_attribute('min'))

6881

6882 add_newdoc('numpy.core.numerictypes', 'generic', ('newbyteorder',

6883 """

6884 newbyteorder(new_order='S', /)

6885

6886 Return a new `dtype` with a different byte order.

6887

6888 Changes are also made in all fields and sub-arrays of the data type.

6889

6890 The `new_order` code can be any from the following:

6891

6892 * 'S' - swap dtype from current to opposite endian

6893 * {'<', 'little'} - little endian

6894 * {'>', 'big'} - big endian

6895 * {'=', 'native'} - native order

6896 * {'|', 'I'} - ignore (no change to byte order)

6897

6898 Parameters

6899 ----------

6900 new_order : str, optional

6901 Byte order to force; a value from the byte order specifications

6902 above. The default value ('S') results in swapping the current

6903 byte order.

6904

6905

6906 Returns

6907 -------

6908 new_dtype : dtype

6909 New `dtype` object with the given change to the byte order.

6910

6911 """))

6912

6913 add_newdoc('numpy.core.numerictypes', 'generic',

6914 refer_to_array_attribute('nonzero'))

6915

6916 add_newdoc('numpy.core.numerictypes', 'generic',

6917 refer_to_array_attribute('prod'))

6918

6919 add_newdoc('numpy.core.numerictypes', 'generic',

6920 refer_to_array_attribute('ptp'))

6921

6922 add_newdoc('numpy.core.numerictypes', 'generic',

6923 refer_to_array_attribute('put'))

6924

6925 add_newdoc('numpy.core.numerictypes', 'generic',

6926 refer_to_array_attribute('ravel'))

6927

6928 add_newdoc('numpy.core.numerictypes', 'generic',

6929 refer_to_array_attribute('repeat'))

6930

6931 add_newdoc('numpy.core.numerictypes', 'generic',

6932 refer_to_array_attribute('reshape'))

6933

6934 add_newdoc('numpy.core.numerictypes', 'generic',

6935 refer_to_array_attribute('resize'))

6936

6937 add_newdoc('numpy.core.numerictypes', 'generic',

6938 refer_to_array_attribute('round'))

6939

6940 add_newdoc('numpy.core.numerictypes', 'generic',

6941 refer_to_array_attribute('searchsorted'))

6942

6943 add_newdoc('numpy.core.numerictypes', 'generic',

6944 refer_to_array_attribute('setfield'))

6945

6946 add_newdoc('numpy.core.numerictypes', 'generic',

6947 refer_to_array_attribute('setflags'))

6948

6949 add_newdoc('numpy.core.numerictypes', 'generic',

6950 refer_to_array_attribute('sort'))

6951

6952 add_newdoc('numpy.core.numerictypes', 'generic',

6953 refer_to_array_attribute('squeeze'))

6954

6955 add_newdoc('numpy.core.numerictypes', 'generic',

6956 refer_to_array_attribute('std'))

6957

6958 add_newdoc('numpy.core.numerictypes', 'generic',

6959 refer_to_array_attribute('sum'))

6960

6961 add_newdoc('numpy.core.numerictypes', 'generic',

6962 refer_to_array_attribute('swapaxes'))

6963

6964 add_newdoc('numpy.core.numerictypes', 'generic',

6965 refer_to_array_attribute('take'))

6966

6967 add_newdoc('numpy.core.numerictypes', 'generic',

6968 refer_to_array_attribute('tofile'))

6969

6970 add_newdoc('numpy.core.numerictypes', 'generic',

6971 refer_to_array_attribute('tolist'))

6972

6973 add_newdoc('numpy.core.numerictypes', 'generic',

6974 refer_to_array_attribute('tostring'))

6975

6976 add_newdoc('numpy.core.numerictypes', 'generic',

6977 refer_to_array_attribute('trace'))

6978

6979 add_newdoc('numpy.core.numerictypes', 'generic',

6980 refer_to_array_attribute('transpose'))

6981

6982 add_newdoc('numpy.core.numerictypes', 'generic',

6983 refer_to_array_attribute('var'))

6984

6985 add_newdoc('numpy.core.numerictypes', 'generic',

6986 refer_to_array_attribute('view'))

6987

6988 add_newdoc('numpy.core.numerictypes', 'number', ('__class_getitem__',

6989 """

6990 __class_getitem__(item, /)

6991

6992 Return a parametrized wrapper around the `~numpy.number` type.

6993

6994 .. versionadded:: 1.22

6995

6996 Returns

6997 -------

6998 alias : types.GenericAlias

6999 A parametrized `~numpy.number` type.

7000

7001 Examples

7002 --------

7003 >>> from typing import Any

7004 >>> import numpy as np

7005

7006 >>> np.signedinteger[Any]

7007 numpy.signedinteger[typing.Any]

7008

7009 Notes

7010 -----

7011 This method is only available for python 3.9 and later.

7012

7013 See Also

7014 --------

7015 :pep:`585` : Type hinting generics in standard collections.

7016

7017 """))

7018

7019##############################################################################

7020#

7021# Documentation for scalar type abstract base classes in type hierarchy

7022#

7023##############################################################################

7024

7025

7026 add_newdoc('numpy.core.numerictypes', 'number',

7027 """

7028 Abstract base class of all numeric scalar types.

7029

7030 """)

7031

7032 add_newdoc('numpy.core.numerictypes', 'integer',

7033 """

7034 Abstract base class of all integer scalar types.

7035

7036 """)

7037

7038 add_newdoc('numpy.core.numerictypes', 'signedinteger',

7039 """

7040 Abstract base class of all signed integer scalar types.

7041

7042 """)

7043

7044 add_newdoc('numpy.core.numerictypes', 'unsignedinteger',

7045 """

7046 Abstract base class of all unsigned integer scalar types.

7047

7048 """)

7049

7050 add_newdoc('numpy.core.numerictypes', 'inexact',

7051 """

7052 Abstract base class of all numeric scalar types with a (potentially)

7053 inexact representation of the values in its range, such as

7054 floating-point numbers.

7055

7056 """)

7057

7058 add_newdoc('numpy.core.numerictypes', 'floating',

7059 """

7060 Abstract base class of all floating-point scalar types.

7061

7062 """)

7063

7064 add_newdoc('numpy.core.numerictypes', 'complexfloating',

7065 """

7066 Abstract base class of all complex number scalar types that are made up of

7067 floating-point numbers.

7068

7069 """)

7070

7071 add_newdoc('numpy.core.numerictypes', 'flexible',

7072 """

7073 Abstract base class of all scalar types without predefined length.

7074 The actual size of these types depends on the specific `np.dtype`

7075 instantiation.

7076

7077 """)

7078

7079 add_newdoc('numpy.core.numerictypes', 'character',

7080 """

7081 Abstract base class of all character string scalar types.

7082

7083 """)