Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/numpy/_core/multiarray.py: 3%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

111 statements  

1""" 

2Create the numpy._core.multiarray namespace for backward compatibility. 

3In v1.16 the multiarray and umath c-extension modules were merged into 

4a single _multiarray_umath extension module. So we replicate the old 

5namespace by importing from the extension module. 

6 

7""" 

8 

9import functools 

10 

11from . import _multiarray_umath, overrides 

12from ._multiarray_umath import * # noqa: F403 

13 

14# These imports are needed for backward compatibility, 

15# do not change them. issue gh-15518 

16# _get_ndarray_c_version is semi-public, on purpose not added to __all__ 

17from ._multiarray_umath import ( # noqa: F401 

18 _ARRAY_API, 

19 _flagdict, 

20 _get_madvise_hugepage, 

21 _get_ndarray_c_version, 

22 _monotonicity, 

23 _place, 

24 _reconstruct, 

25 _set_madvise_hugepage, 

26 _vec_string, 

27 from_dlpack, 

28) 

29 

30__all__ = [ 

31 '_ARRAY_API', 'ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'DATETIMEUNITS', 

32 'ITEM_HASOBJECT', 'ITEM_IS_POINTER', 'LIST_PICKLE', 'MAXDIMS', 

33 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', 'NEEDS_INIT', 'NEEDS_PYAPI', 

34 'RAISE', 'USE_GETITEM', 'USE_SETITEM', 'WRAP', 

35 '_flagdict', 'from_dlpack', '_place', '_reconstruct', '_vec_string', 

36 '_monotonicity', 'add_docstring', 'arange', 'array', 'asarray', 

37 'asanyarray', 'ascontiguousarray', 'asfortranarray', 'bincount', 

38 'broadcast', 'busday_count', 'busday_offset', 'busdaycalendar', 'can_cast', 

39 'compare_chararrays', 'concatenate', 'copyto', 'correlate', 'correlate2', 

40 'count_nonzero', 'c_einsum', 'datetime_as_string', 'datetime_data', 

41 'dot', 'dragon4_positional', 'dragon4_scientific', 'dtype', 

42 'empty', 'empty_like', 'error', 'flagsobj', 'flatiter', 'format_longfloat', 

43 'frombuffer', 'fromfile', 'fromiter', 'fromstring', 

44 'get_handler_name', 'get_handler_version', 'inner', 'interp', 

45 'interp_complex', 'is_busday', 'lexsort', 'matmul', 'vecdot', 

46 'may_share_memory', 'min_scalar_type', 'ndarray', 'nditer', 'nested_iters', 

47 'normalize_axis_index', 'packbits', 'promote_types', 'putmask', 

48 'ravel_multi_index', 'result_type', 'scalar', 'set_datetimeparse_function', 

49 'set_typeDict', 'shares_memory', 'typeinfo', 

50 'unpackbits', 'unravel_index', 'vdot', 'where', 'zeros'] 

51 

52# For backward compatibility, make sure pickle imports 

53# these functions from here 

54_reconstruct.__module__ = 'numpy._core.multiarray' 

55scalar.__module__ = 'numpy._core.multiarray' 

56 

57 

58from_dlpack.__module__ = 'numpy' 

59arange.__module__ = 'numpy' 

60array.__module__ = 'numpy' 

61asarray.__module__ = 'numpy' 

62asanyarray.__module__ = 'numpy' 

63ascontiguousarray.__module__ = 'numpy' 

64asfortranarray.__module__ = 'numpy' 

65datetime_data.__module__ = 'numpy' 

66empty.__module__ = 'numpy' 

67frombuffer.__module__ = 'numpy' 

68fromfile.__module__ = 'numpy' 

69fromiter.__module__ = 'numpy' 

70frompyfunc.__module__ = 'numpy' 

71fromstring.__module__ = 'numpy' 

72may_share_memory.__module__ = 'numpy' 

73nested_iters.__module__ = 'numpy' 

74promote_types.__module__ = 'numpy' 

75zeros.__module__ = 'numpy' 

76normalize_axis_index.__module__ = 'numpy.lib.array_utils' 

77add_docstring.__module__ = 'numpy.lib' 

78compare_chararrays.__module__ = 'numpy.char' 

79 

80 

81def _override___module__(): 

82 namespace_names = globals() 

83 for ufunc_name in [ 

84 'absolute', 'arccos', 'arccosh', 'add', 'arcsin', 'arcsinh', 'arctan', 

85 'arctan2', 'arctanh', 'bitwise_and', 'bitwise_count', 'invert', 

86 'left_shift', 'bitwise_or', 'right_shift', 'bitwise_xor', 'cbrt', 

87 'ceil', 'conjugate', 'copysign', 'cos', 'cosh', 'deg2rad', 'degrees', 

88 'divide', 'divmod', 'equal', 'exp', 'exp2', 'expm1', 'fabs', 

89 'float_power', 'floor', 'floor_divide', 'fmax', 'fmin', 'fmod', 

90 'frexp', 'gcd', 'greater', 'greater_equal', 'heaviside', 'hypot', 

91 'isfinite', 'isinf', 'isnan', 'isnat', 'lcm', 'ldexp', 'less', 

92 'less_equal', 'log', 'log10', 'log1p', 'log2', 'logaddexp', 

93 'logaddexp2', 'logical_and', 'logical_not', 'logical_or', 

94 'logical_xor', 'matmul', 'matvec', 'maximum', 'minimum', 'remainder', 

95 'modf', 'multiply', 'negative', 'nextafter', 'not_equal', 'positive', 

96 'power', 'rad2deg', 'radians', 'reciprocal', 'rint', 'sign', 'signbit', 

97 'sin', 'sinh', 'spacing', 'sqrt', 'square', 'subtract', 'tan', 'tanh', 

98 'trunc', 'vecdot', 'vecmat', 

99 ]: 

100 ufunc = namespace_names[ufunc_name] 

101 ufunc.__module__ = "numpy" 

102 ufunc.__qualname__ = ufunc_name 

103 

104 

105_override___module__() 

106 

107 

108# We can't verify dispatcher signatures because NumPy's C functions don't 

109# support introspection. 

110array_function_from_c_func_and_dispatcher = functools.partial( 

111 overrides.array_function_from_dispatcher, 

112 module='numpy', docs_from_dispatcher=True, verify=False) 

113 

114 

115@array_function_from_c_func_and_dispatcher(_multiarray_umath.empty_like) 

116def empty_like( 

117 prototype, dtype=None, order=None, subok=None, shape=None, *, device=None 

118): 

119 """ 

120 empty_like(prototype, dtype=None, order='K', subok=True, shape=None, *, 

121 device=None) 

122 

123 Return a new array with the same shape and type as a given array. 

124 

125 Parameters 

126 ---------- 

127 prototype : array_like 

128 The shape and data-type of `prototype` define these same attributes 

129 of the returned array. 

130 dtype : data-type, optional 

131 Overrides the data type of the result. 

132 order : {'C', 'F', 'A', or 'K'}, optional 

133 Overrides the memory layout of the result. 'C' means C-order, 

134 'F' means F-order, 'A' means 'F' if `prototype` is Fortran 

135 contiguous, 'C' otherwise. 'K' means match the layout of `prototype` 

136 as closely as possible. 

137 subok : bool, optional. 

138 If True, then the newly created array will use the sub-class 

139 type of `prototype`, otherwise it will be a base-class array. Defaults 

140 to True. 

141 shape : int or sequence of ints, optional. 

142 Overrides the shape of the result. If order='K' and the number of 

143 dimensions is unchanged, will try to keep order, otherwise, 

144 order='C' is implied. 

145 device : str, optional 

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

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

148 

149 .. versionadded:: 2.0.0 

150 

151 Returns 

152 ------- 

153 out : ndarray 

154 Array of uninitialized (arbitrary) data with the same 

155 shape and type as `prototype`. 

156 

157 See Also 

158 -------- 

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

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

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

162 empty : Return a new uninitialized array. 

163 

164 Notes 

165 ----- 

166 Unlike other array creation functions (e.g. `zeros_like`, `ones_like`, 

167 `full_like`), `empty_like` does not initialize the values of the array, 

168 and may therefore be marginally faster. However, the values stored in the 

169 newly allocated array are arbitrary. For reproducible behavior, be sure 

170 to set each element of the array before reading. 

171 

172 Examples 

173 -------- 

174 >>> import numpy as np 

175 >>> a = ([1,2,3], [4,5,6]) # a is array-like 

176 >>> np.empty_like(a) 

177 array([[-1073741821, -1073741821, 3], # uninitialized 

178 [ 0, 0, -1073741821]]) 

179 >>> a = np.array([[1., 2., 3.],[4.,5.,6.]]) 

180 >>> np.empty_like(a) 

181 array([[ -2.00000715e+000, 1.48219694e-323, -2.00000572e+000], # uninitialized 

182 [ 4.38791518e-305, -2.00000715e+000, 4.17269252e-309]]) 

183 

184 """ 

185 return (prototype,) 

186 

187 

188@array_function_from_c_func_and_dispatcher(_multiarray_umath.concatenate) 

189def concatenate(arrays, axis=None, out=None, *, dtype=None, casting=None): 

190 """ 

191 concatenate( 

192 (a1, a2, ...), 

193 axis=0, 

194 out=None, 

195 dtype=None, 

196 casting="same_kind" 

197 ) 

198 

199 Join a sequence of arrays along an existing axis. 

200 

201 Parameters 

202 ---------- 

203 a1, a2, ... : sequence of array_like 

204 The arrays must have the same shape, except in the dimension 

205 corresponding to `axis` (the first, by default). 

206 axis : int, optional 

207 The axis along which the arrays will be joined. If axis is None, 

208 arrays are flattened before use. Default is 0. 

209 out : ndarray, optional 

210 If provided, the destination to place the result. The shape must be 

211 correct, matching that of what concatenate would have returned if no 

212 out argument were specified. 

213 dtype : str or dtype 

214 If provided, the destination array will have this dtype. Cannot be 

215 provided together with `out`. 

216 

217 .. versionadded:: 1.20.0 

218 

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

220 Controls what kind of data casting may occur. Defaults to 'same_kind'. 

221 For a description of the options, please see :term:`casting`. 

222 

223 .. versionadded:: 1.20.0 

224 

225 Returns 

226 ------- 

227 res : ndarray 

228 The concatenated array. 

229 

230 See Also 

231 -------- 

232 ma.concatenate : Concatenate function that preserves input masks. 

233 array_split : Split an array into multiple sub-arrays of equal or 

234 near-equal size. 

235 split : Split array into a list of multiple sub-arrays of equal size. 

236 hsplit : Split array into multiple sub-arrays horizontally (column wise). 

237 vsplit : Split array into multiple sub-arrays vertically (row wise). 

238 dsplit : Split array into multiple sub-arrays along the 3rd axis (depth). 

239 stack : Stack a sequence of arrays along a new axis. 

240 block : Assemble arrays from blocks. 

241 hstack : Stack arrays in sequence horizontally (column wise). 

242 vstack : Stack arrays in sequence vertically (row wise). 

243 dstack : Stack arrays in sequence depth wise (along third dimension). 

244 column_stack : Stack 1-D arrays as columns into a 2-D array. 

245 

246 Notes 

247 ----- 

248 When one or more of the arrays to be concatenated is a MaskedArray, 

249 this function will return a MaskedArray object instead of an ndarray, 

250 but the input masks are *not* preserved. In cases where a MaskedArray 

251 is expected as input, use the ma.concatenate function from the masked 

252 array module instead. 

253 

254 Examples 

255 -------- 

256 >>> import numpy as np 

257 >>> a = np.array([[1, 2], [3, 4]]) 

258 >>> b = np.array([[5, 6]]) 

259 >>> np.concatenate((a, b), axis=0) 

260 array([[1, 2], 

261 [3, 4], 

262 [5, 6]]) 

263 >>> np.concatenate((a, b.T), axis=1) 

264 array([[1, 2, 5], 

265 [3, 4, 6]]) 

266 >>> np.concatenate((a, b), axis=None) 

267 array([1, 2, 3, 4, 5, 6]) 

268 

269 This function will not preserve masking of MaskedArray inputs. 

270 

271 >>> a = np.ma.arange(3) 

272 >>> a[1] = np.ma.masked 

273 >>> b = np.arange(2, 5) 

274 >>> a 

275 masked_array(data=[0, --, 2], 

276 mask=[False, True, False], 

277 fill_value=999999) 

278 >>> b 

279 array([2, 3, 4]) 

280 >>> np.concatenate([a, b]) 

281 masked_array(data=[0, 1, 2, 2, 3, 4], 

282 mask=False, 

283 fill_value=999999) 

284 >>> np.ma.concatenate([a, b]) 

285 masked_array(data=[0, --, 2, 2, 3, 4], 

286 mask=[False, True, False, False, False, False], 

287 fill_value=999999) 

288 

289 """ 

290 if out is not None: 

291 # optimize for the typical case where only arrays is provided 

292 arrays = list(arrays) 

293 arrays.append(out) 

294 return arrays 

295 

296 

297@array_function_from_c_func_and_dispatcher(_multiarray_umath.inner) 

298def inner(a, b): 

299 """ 

300 inner(a, b, /) 

301 

302 Inner product of two arrays. 

303 

304 Ordinary inner product of vectors for 1-D arrays (without complex 

305 conjugation), in higher dimensions a sum product over the last axes. 

306 

307 Parameters 

308 ---------- 

309 a, b : array_like 

310 If `a` and `b` are nonscalar, their last dimensions must match. 

311 

312 Returns 

313 ------- 

314 out : ndarray 

315 If `a` and `b` are both 

316 scalars or both 1-D arrays then a scalar is returned; otherwise 

317 an array is returned. 

318 ``out.shape = (*a.shape[:-1], *b.shape[:-1])`` 

319 

320 Raises 

321 ------ 

322 ValueError 

323 If both `a` and `b` are nonscalar and their last dimensions have 

324 different sizes. 

325 

326 See Also 

327 -------- 

328 tensordot : Sum products over arbitrary axes. 

329 dot : Generalised matrix product, using second last dimension of `b`. 

330 vecdot : Vector dot product of two arrays. 

331 einsum : Einstein summation convention. 

332 

333 Notes 

334 ----- 

335 For vectors (1-D arrays) it computes the ordinary inner-product:: 

336 

337 np.inner(a, b) = sum(a[:]*b[:]) 

338 

339 More generally, if ``ndim(a) = r > 0`` and ``ndim(b) = s > 0``:: 

340 

341 np.inner(a, b) = np.tensordot(a, b, axes=(-1,-1)) 

342 

343 or explicitly:: 

344 

345 np.inner(a, b)[i0,...,ir-2,j0,...,js-2] 

346 = sum(a[i0,...,ir-2,:]*b[j0,...,js-2,:]) 

347 

348 In addition `a` or `b` may be scalars, in which case:: 

349 

350 np.inner(a,b) = a*b 

351 

352 Examples 

353 -------- 

354 Ordinary inner product for vectors: 

355 

356 >>> import numpy as np 

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

358 >>> b = np.array([0,1,0]) 

359 >>> np.inner(a, b) 

360 2 

361 

362 Some multidimensional examples: 

363 

364 >>> a = np.arange(24).reshape((2,3,4)) 

365 >>> b = np.arange(4) 

366 >>> c = np.inner(a, b) 

367 >>> c.shape 

368 (2, 3) 

369 >>> c 

370 array([[ 14, 38, 62], 

371 [ 86, 110, 134]]) 

372 

373 >>> a = np.arange(2).reshape((1,1,2)) 

374 >>> b = np.arange(6).reshape((3,2)) 

375 >>> c = np.inner(a, b) 

376 >>> c.shape 

377 (1, 1, 3) 

378 >>> c 

379 array([[[1, 3, 5]]]) 

380 

381 An example where `b` is a scalar: 

382 

383 >>> np.inner(np.eye(2), 7) 

384 array([[7., 0.], 

385 [0., 7.]]) 

386 

387 """ 

388 return (a, b) 

389 

390 

391@array_function_from_c_func_and_dispatcher(_multiarray_umath.where) 

392def where(condition, x=None, y=None): 

393 """ 

394 where(condition, [x, y], /) 

395 

396 Return elements chosen from `x` or `y` depending on `condition`. 

397 

398 .. note:: 

399 When only `condition` is provided, this function is a shorthand for 

400 ``np.asarray(condition).nonzero()``. Using `nonzero` directly should be 

401 preferred, as it behaves correctly for subclasses. The rest of this 

402 documentation covers only the case where all three arguments are 

403 provided. 

404 

405 Parameters 

406 ---------- 

407 condition : array_like, bool 

408 Where True, yield `x`, otherwise yield `y`. 

409 x, y : array_like 

410 Values from which to choose. `x`, `y` and `condition` need to be 

411 broadcastable to some shape. 

412 

413 Returns 

414 ------- 

415 out : ndarray 

416 An array with elements from `x` where `condition` is True, and elements 

417 from `y` elsewhere. 

418 

419 See Also 

420 -------- 

421 choose 

422 nonzero : The function that is called when x and y are omitted 

423 

424 Notes 

425 ----- 

426 If all the arrays are 1-D, `where` is equivalent to:: 

427 

428 [xv if c else yv 

429 for c, xv, yv in zip(condition, x, y)] 

430 

431 Examples 

432 -------- 

433 >>> import numpy as np 

434 >>> a = np.arange(10) 

435 >>> a 

436 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 

437 >>> np.where(a < 5, a, 10*a) 

438 array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90]) 

439 

440 This can be used on multidimensional arrays too: 

441 

442 >>> np.where([[True, False], [True, True]], 

443 ... [[1, 2], [3, 4]], 

444 ... [[9, 8], [7, 6]]) 

445 array([[1, 8], 

446 [3, 4]]) 

447 

448 The shapes of x, y, and the condition are broadcast together: 

449 

450 >>> x, y = np.ogrid[:3, :4] 

451 >>> np.where(x < y, x, 10 + y) # both x and 10+y are broadcast 

452 array([[10, 0, 0, 0], 

453 [10, 11, 1, 1], 

454 [10, 11, 12, 2]]) 

455 

456 >>> a = np.array([[0, 1, 2], 

457 ... [0, 2, 4], 

458 ... [0, 3, 6]]) 

459 >>> np.where(a < 4, a, -1) # -1 is broadcast 

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

461 [ 0, 2, -1], 

462 [ 0, 3, -1]]) 

463 """ 

464 return (condition, x, y) 

465 

466 

467@array_function_from_c_func_and_dispatcher(_multiarray_umath.lexsort) 

468def lexsort(keys, axis=None): 

469 """ 

470 lexsort(keys, axis=-1) 

471 

472 Perform an indirect stable sort using a sequence of keys. 

473 

474 Given multiple sorting keys, lexsort returns an array of integer indices 

475 that describes the sort order by multiple keys. The last key in the 

476 sequence is used for the primary sort order, ties are broken by the 

477 second-to-last key, and so on. 

478 

479 Parameters 

480 ---------- 

481 keys : (k, m, n, ...) array-like 

482 The `k` keys to be sorted. The *last* key (e.g, the last 

483 row if `keys` is a 2D array) is the primary sort key. 

484 Each element of `keys` along the zeroth axis must be 

485 an array-like object of the same shape. 

486 axis : int, optional 

487 Axis to be indirectly sorted. By default, sort over the last axis 

488 of each sequence. Separate slices along `axis` sorted over 

489 independently; see last example. 

490 

491 Returns 

492 ------- 

493 indices : (m, n, ...) ndarray of ints 

494 Array of indices that sort the keys along the specified axis. 

495 

496 See Also 

497 -------- 

498 argsort : Indirect sort. 

499 ndarray.sort : In-place sort. 

500 sort : Return a sorted copy of an array. 

501 

502 Examples 

503 -------- 

504 Sort names: first by surname, then by name. 

505 

506 >>> import numpy as np 

507 >>> surnames = ('Hertz', 'Galilei', 'Hertz') 

508 >>> first_names = ('Heinrich', 'Galileo', 'Gustav') 

509 >>> ind = np.lexsort((first_names, surnames)) 

510 >>> ind 

511 array([1, 2, 0]) 

512 

513 >>> [surnames[i] + ", " + first_names[i] for i in ind] 

514 ['Galilei, Galileo', 'Hertz, Gustav', 'Hertz, Heinrich'] 

515 

516 Sort according to two numerical keys, first by elements 

517 of ``a``, then breaking ties according to elements of ``b``: 

518 

519 >>> a = [1, 5, 1, 4, 3, 4, 4] # First sequence 

520 >>> b = [9, 4, 0, 4, 0, 2, 1] # Second sequence 

521 >>> ind = np.lexsort((b, a)) # Sort by `a`, then by `b` 

522 >>> ind 

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

524 >>> [(a[i], b[i]) for i in ind] 

525 [(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)] 

526 

527 Compare against `argsort`, which would sort each key independently. 

528 

529 >>> np.argsort((b, a), kind='stable') 

530 array([[2, 4, 6, 5, 1, 3, 0], 

531 [0, 2, 4, 3, 5, 6, 1]]) 

532 

533 To sort lexicographically with `argsort`, we would need to provide a 

534 structured array. 

535 

536 >>> x = np.array([(ai, bi) for ai, bi in zip(a, b)], 

537 ... dtype = np.dtype([('x', int), ('y', int)])) 

538 >>> np.argsort(x) # or np.argsort(x, order=('x', 'y')) 

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

540 

541 The zeroth axis of `keys` always corresponds with the sequence of keys, 

542 so 2D arrays are treated just like other sequences of keys. 

543 

544 >>> arr = np.asarray([b, a]) 

545 >>> ind2 = np.lexsort(arr) 

546 >>> np.testing.assert_equal(ind2, ind) 

547 

548 Accordingly, the `axis` parameter refers to an axis of *each* key, not of 

549 the `keys` argument itself. For instance, the array ``arr`` is treated as 

550 a sequence of two 1-D keys, so specifying ``axis=0`` is equivalent to 

551 using the default axis, ``axis=-1``. 

552 

553 >>> np.testing.assert_equal(np.lexsort(arr, axis=0), 

554 ... np.lexsort(arr, axis=-1)) 

555 

556 For higher-dimensional arrays, the axis parameter begins to matter. The 

557 resulting array has the same shape as each key, and the values are what 

558 we would expect if `lexsort` were performed on corresponding slices 

559 of the keys independently. For instance, 

560 

561 >>> x = [[1, 2, 3, 4], 

562 ... [4, 3, 2, 1], 

563 ... [2, 1, 4, 3]] 

564 >>> y = [[2, 2, 1, 1], 

565 ... [1, 2, 1, 2], 

566 ... [1, 1, 2, 1]] 

567 >>> np.lexsort((x, y), axis=1) 

568 array([[2, 3, 0, 1], 

569 [2, 0, 3, 1], 

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

571 

572 Each row of the result is what we would expect if we were to perform 

573 `lexsort` on the corresponding row of the keys: 

574 

575 >>> for i in range(3): 

576 ... print(np.lexsort((x[i], y[i]))) 

577 [2 3 0 1] 

578 [2 0 3 1] 

579 [1 0 3 2] 

580 

581 """ 

582 if isinstance(keys, tuple): 

583 return keys 

584 else: 

585 return (keys,) 

586 

587 

588@array_function_from_c_func_and_dispatcher(_multiarray_umath.can_cast) 

589def can_cast(from_, to, casting=None): 

590 """ 

591 can_cast(from_, to, casting='safe') 

592 

593 Returns True if cast between data types can occur according to the 

594 casting rule. 

595 

596 Parameters 

597 ---------- 

598 from_ : dtype, dtype specifier, NumPy scalar, or array 

599 Data type, NumPy scalar, or array to cast from. 

600 to : dtype or dtype specifier 

601 Data type to cast to. 

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

603 Controls what kind of data casting may occur. 

604 

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

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

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

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

609 like float64 to float32, are allowed. 

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

611 

612 Returns 

613 ------- 

614 out : bool 

615 True if cast can occur according to the casting rule. 

616 

617 Notes 

618 ----- 

619 .. versionchanged:: 2.0 

620 This function does not support Python scalars anymore and does not 

621 apply any value-based logic for 0-D arrays and NumPy scalars. 

622 

623 See also 

624 -------- 

625 dtype, result_type 

626 

627 Examples 

628 -------- 

629 Basic examples 

630 

631 >>> import numpy as np 

632 >>> np.can_cast(np.int32, np.int64) 

633 True 

634 >>> np.can_cast(np.float64, complex) 

635 True 

636 >>> np.can_cast(complex, float) 

637 False 

638 

639 >>> np.can_cast('i8', 'f8') 

640 True 

641 >>> np.can_cast('i8', 'f4') 

642 False 

643 >>> np.can_cast('i4', 'S4') 

644 False 

645 

646 """ 

647 return (from_,) 

648 

649 

650@array_function_from_c_func_and_dispatcher(_multiarray_umath.min_scalar_type) 

651def min_scalar_type(a): 

652 """ 

653 min_scalar_type(a, /) 

654 

655 For scalar ``a``, returns the data type with the smallest size 

656 and smallest scalar kind which can hold its value. For non-scalar 

657 array ``a``, returns the vector's dtype unmodified. 

658 

659 Floating point values are not demoted to integers, 

660 and complex values are not demoted to floats. 

661 

662 Parameters 

663 ---------- 

664 a : scalar or array_like 

665 The value whose minimal data type is to be found. 

666 

667 Returns 

668 ------- 

669 out : dtype 

670 The minimal data type. 

671 

672 See Also 

673 -------- 

674 result_type, promote_types, dtype, can_cast 

675 

676 Examples 

677 -------- 

678 >>> import numpy as np 

679 >>> np.min_scalar_type(10) 

680 dtype('uint8') 

681 

682 >>> np.min_scalar_type(-260) 

683 dtype('int16') 

684 

685 >>> np.min_scalar_type(3.1) 

686 dtype('float16') 

687 

688 >>> np.min_scalar_type(1e50) 

689 dtype('float64') 

690 

691 >>> np.min_scalar_type(np.arange(4,dtype='f8')) 

692 dtype('float64') 

693 

694 """ 

695 return (a,) 

696 

697 

698@array_function_from_c_func_and_dispatcher(_multiarray_umath.result_type) 

699def result_type(*arrays_and_dtypes): 

700 """ 

701 result_type(*arrays_and_dtypes) 

702 

703 Returns the type that results from applying the NumPy 

704 type promotion rules to the arguments. 

705 

706 Type promotion in NumPy works similarly to the rules in languages 

707 like C++, with some slight differences. When both scalars and 

708 arrays are used, the array's type takes precedence and the actual value 

709 of the scalar is taken into account. 

710 

711 For example, calculating 3*a, where a is an array of 32-bit floats, 

712 intuitively should result in a 32-bit float output. If the 3 is a 

713 32-bit integer, the NumPy rules indicate it can't convert losslessly 

714 into a 32-bit float, so a 64-bit float should be the result type. 

715 By examining the value of the constant, '3', we see that it fits in 

716 an 8-bit integer, which can be cast losslessly into the 32-bit float. 

717 

718 Parameters 

719 ---------- 

720 arrays_and_dtypes : list of arrays and dtypes 

721 The operands of some operation whose result type is needed. 

722 

723 Returns 

724 ------- 

725 out : dtype 

726 The result type. 

727 

728 See also 

729 -------- 

730 dtype, promote_types, min_scalar_type, can_cast 

731 

732 Notes 

733 ----- 

734 The specific algorithm used is as follows. 

735 

736 Categories are determined by first checking which of boolean, 

737 integer (int/uint), or floating point (float/complex) the maximum 

738 kind of all the arrays and the scalars are. 

739 

740 If there are only scalars or the maximum category of the scalars 

741 is higher than the maximum category of the arrays, 

742 the data types are combined with :func:`promote_types` 

743 to produce the return value. 

744 

745 Otherwise, `min_scalar_type` is called on each scalar, and 

746 the resulting data types are all combined with :func:`promote_types` 

747 to produce the return value. 

748 

749 The set of int values is not a subset of the uint values for types 

750 with the same number of bits, something not reflected in 

751 :func:`min_scalar_type`, but handled as a special case in `result_type`. 

752 

753 Examples 

754 -------- 

755 >>> import numpy as np 

756 >>> np.result_type(3, np.arange(7, dtype='i1')) 

757 dtype('int8') 

758 

759 >>> np.result_type('i4', 'c8') 

760 dtype('complex128') 

761 

762 >>> np.result_type(3.0, -2) 

763 dtype('float64') 

764 

765 """ 

766 return arrays_and_dtypes 

767 

768 

769@array_function_from_c_func_and_dispatcher(_multiarray_umath.dot) 

770def dot(a, b, out=None): 

771 """ 

772 dot(a, b, out=None) 

773 

774 Dot product of two arrays. Specifically, 

775 

776 - If both `a` and `b` are 1-D arrays, it is inner product of vectors 

777 (without complex conjugation). 

778 

779 - If both `a` and `b` are 2-D arrays, it is matrix multiplication, 

780 but using :func:`matmul` or ``a @ b`` is preferred. 

781 

782 - If either `a` or `b` is 0-D (scalar), it is equivalent to 

783 :func:`multiply` and using ``numpy.multiply(a, b)`` or ``a * b`` is 

784 preferred. 

785 

786 - If `a` is an N-D array and `b` is a 1-D array, it is a sum product over 

787 the last axis of `a` and `b`. 

788 

789 - If `a` is an N-D array and `b` is an M-D array (where ``M>=2``), it is a 

790 sum product over the last axis of `a` and the second-to-last axis of 

791 `b`:: 

792 

793 dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m]) 

794 

795 It uses an optimized BLAS library when possible (see `numpy.linalg`). 

796 

797 Parameters 

798 ---------- 

799 a : array_like 

800 First argument. 

801 b : array_like 

802 Second argument. 

803 out : ndarray, optional 

804 Output argument. This must have the exact kind that would be returned 

805 if it was not used. In particular, it must have the right type, must be 

806 C-contiguous, and its dtype must be the dtype that would be returned 

807 for `dot(a,b)`. This is a performance feature. Therefore, if these 

808 conditions are not met, an exception is raised, instead of attempting 

809 to be flexible. 

810 

811 Returns 

812 ------- 

813 output : ndarray 

814 Returns the dot product of `a` and `b`. If `a` and `b` are both 

815 scalars or both 1-D arrays then a scalar is returned; otherwise 

816 an array is returned. 

817 If `out` is given, then it is returned. 

818 

819 Raises 

820 ------ 

821 ValueError 

822 If the last dimension of `a` is not the same size as 

823 the second-to-last dimension of `b`. 

824 

825 See Also 

826 -------- 

827 vdot : Complex-conjugating dot product. 

828 vecdot : Vector dot product of two arrays. 

829 tensordot : Sum products over arbitrary axes. 

830 einsum : Einstein summation convention. 

831 matmul : '@' operator as method with out parameter. 

832 linalg.multi_dot : Chained dot product. 

833 

834 Examples 

835 -------- 

836 >>> import numpy as np 

837 >>> np.dot(3, 4) 

838 12 

839 

840 Neither argument is complex-conjugated: 

841 

842 >>> np.dot([2j, 3j], [2j, 3j]) 

843 (-13+0j) 

844 

845 For 2-D arrays it is the matrix product: 

846 

847 >>> a = [[1, 0], [0, 1]] 

848 >>> b = [[4, 1], [2, 2]] 

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

850 array([[4, 1], 

851 [2, 2]]) 

852 

853 >>> a = np.arange(3*4*5*6).reshape((3,4,5,6)) 

854 >>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3)) 

855 >>> np.dot(a, b)[2,3,2,1,2,2] 

856 499128 

857 >>> sum(a[2,3,2,:] * b[1,2,:,2]) 

858 499128 

859 

860 """ 

861 return (a, b, out) 

862 

863 

864@array_function_from_c_func_and_dispatcher(_multiarray_umath.vdot) 

865def vdot(a, b): 

866 r""" 

867 vdot(a, b, /) 

868 

869 Return the dot product of two vectors. 

870 

871 The `vdot` function handles complex numbers differently than `dot`: 

872 if the first argument is complex, it is replaced by its complex conjugate 

873 in the dot product calculation. `vdot` also handles multidimensional 

874 arrays differently than `dot`: it does not perform a matrix product, but 

875 flattens the arguments to 1-D arrays before taking a vector dot product. 

876 

877 Consequently, when the arguments are 2-D arrays of the same shape, this 

878 function effectively returns their 

879 `Frobenius inner product <https://en.wikipedia.org/wiki/Frobenius_inner_product>`_ 

880 (also known as the *trace inner product* or the *standard inner product* 

881 on a vector space of matrices). 

882 

883 Parameters 

884 ---------- 

885 a : array_like 

886 If `a` is complex the complex conjugate is taken before calculation 

887 of the dot product. 

888 b : array_like 

889 Second argument to the dot product. 

890 

891 Returns 

892 ------- 

893 output : ndarray 

894 Dot product of `a` and `b`. Can be an int, float, or 

895 complex depending on the types of `a` and `b`. 

896 

897 See Also 

898 -------- 

899 dot : Return the dot product without using the complex conjugate of the 

900 first argument. 

901 

902 Examples 

903 -------- 

904 >>> import numpy as np 

905 >>> a = np.array([1+2j,3+4j]) 

906 >>> b = np.array([5+6j,7+8j]) 

907 >>> np.vdot(a, b) 

908 (70-8j) 

909 >>> np.vdot(b, a) 

910 (70+8j) 

911 

912 Note that higher-dimensional arrays are flattened! 

913 

914 >>> a = np.array([[1, 4], [5, 6]]) 

915 >>> b = np.array([[4, 1], [2, 2]]) 

916 >>> np.vdot(a, b) 

917 30 

918 >>> np.vdot(b, a) 

919 30 

920 >>> 1*4 + 4*1 + 5*2 + 6*2 

921 30 

922 

923 """ # noqa: E501 

924 return (a, b) 

925 

926 

927@array_function_from_c_func_and_dispatcher(_multiarray_umath.bincount) 

928def bincount(x, weights=None, minlength=None): 

929 """ 

930 bincount(x, /, weights=None, minlength=0) 

931 

932 Count number of occurrences of each value in array of non-negative ints. 

933 

934 The number of bins (of size 1) is one larger than the largest value in 

935 `x`. If `minlength` is specified, there will be at least this number 

936 of bins in the output array (though it will be longer if necessary, 

937 depending on the contents of `x`). 

938 Each bin gives the number of occurrences of its index value in `x`. 

939 If `weights` is specified the input array is weighted by it, i.e. if a 

940 value ``n`` is found at position ``i``, ``out[n] += weight[i]`` instead 

941 of ``out[n] += 1``. 

942 

943 Parameters 

944 ---------- 

945 x : array_like, 1 dimension, nonnegative ints 

946 Input array. 

947 weights : array_like, optional 

948 Weights, array of the same shape as `x`. 

949 minlength : int, optional 

950 A minimum number of bins for the output array. 

951 

952 Returns 

953 ------- 

954 out : ndarray of ints 

955 The result of binning the input array. 

956 The length of `out` is equal to ``np.amax(x)+1``. 

957 

958 Raises 

959 ------ 

960 ValueError 

961 If the input is not 1-dimensional, or contains elements with negative 

962 values, or if `minlength` is negative. 

963 TypeError 

964 If the type of the input is float or complex. 

965 

966 See Also 

967 -------- 

968 histogram, digitize, unique 

969 

970 Examples 

971 -------- 

972 >>> import numpy as np 

973 >>> np.bincount(np.arange(5)) 

974 array([1, 1, 1, 1, 1]) 

975 >>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7])) 

976 array([1, 3, 1, 1, 0, 0, 0, 1]) 

977 

978 >>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23]) 

979 >>> np.bincount(x).size == np.amax(x)+1 

980 True 

981 

982 The input array needs to be of integer dtype, otherwise a 

983 TypeError is raised: 

984 

985 >>> np.bincount(np.arange(5, dtype=float)) 

986 Traceback (most recent call last): 

987 ... 

988 TypeError: Cannot cast array data from dtype('float64') to dtype('int64') 

989 according to the rule 'safe' 

990 

991 A possible use of ``bincount`` is to perform sums over 

992 variable-size chunks of an array, using the ``weights`` keyword. 

993 

994 >>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights 

995 >>> x = np.array([0, 1, 1, 2, 2, 2]) 

996 >>> np.bincount(x, weights=w) 

997 array([ 0.3, 0.7, 1.1]) 

998 

999 """ 

1000 return (x, weights) 

1001 

1002 

1003@array_function_from_c_func_and_dispatcher(_multiarray_umath.ravel_multi_index) 

1004def ravel_multi_index(multi_index, dims, mode=None, order=None): 

1005 """ 

1006 ravel_multi_index(multi_index, dims, mode='raise', order='C') 

1007 

1008 Converts a tuple of index arrays into an array of flat 

1009 indices, applying boundary modes to the multi-index. 

1010 

1011 Parameters 

1012 ---------- 

1013 multi_index : tuple of array_like 

1014 A tuple of integer arrays, one array for each dimension. 

1015 dims : tuple of ints 

1016 The shape of array into which the indices from ``multi_index`` apply. 

1017 mode : {'raise', 'wrap', 'clip'}, optional 

1018 Specifies how out-of-bounds indices are handled. Can specify 

1019 either one mode or a tuple of modes, one mode per index. 

1020 

1021 * 'raise' -- raise an error (default) 

1022 * 'wrap' -- wrap around 

1023 * 'clip' -- clip to the range 

1024 

1025 In 'clip' mode, a negative index which would normally 

1026 wrap will clip to 0 instead. 

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

1028 Determines whether the multi-index should be viewed as 

1029 indexing in row-major (C-style) or column-major 

1030 (Fortran-style) order. 

1031 

1032 Returns 

1033 ------- 

1034 raveled_indices : ndarray 

1035 An array of indices into the flattened version of an array 

1036 of dimensions ``dims``. 

1037 

1038 See Also 

1039 -------- 

1040 unravel_index 

1041 

1042 Examples 

1043 -------- 

1044 >>> import numpy as np 

1045 >>> arr = np.array([[3,6,6],[4,5,1]]) 

1046 >>> np.ravel_multi_index(arr, (7,6)) 

1047 array([22, 41, 37]) 

1048 >>> np.ravel_multi_index(arr, (7,6), order='F') 

1049 array([31, 41, 13]) 

1050 >>> np.ravel_multi_index(arr, (4,6), mode='clip') 

1051 array([22, 23, 19]) 

1052 >>> np.ravel_multi_index(arr, (4,4), mode=('clip','wrap')) 

1053 array([12, 13, 13]) 

1054 

1055 >>> np.ravel_multi_index((3,1,4,1), (6,7,8,9)) 

1056 1621 

1057 """ 

1058 return multi_index 

1059 

1060 

1061@array_function_from_c_func_and_dispatcher(_multiarray_umath.unravel_index) 

1062def unravel_index(indices, shape=None, order=None): 

1063 """ 

1064 unravel_index(indices, shape, order='C') 

1065 

1066 Converts a flat index or array of flat indices into a tuple 

1067 of coordinate arrays. 

1068 

1069 Parameters 

1070 ---------- 

1071 indices : array_like 

1072 An integer array whose elements are indices into the flattened 

1073 version of an array of dimensions ``shape``. Before version 1.6.0, 

1074 this function accepted just one index value. 

1075 shape : tuple of ints 

1076 The shape of the array to use for unraveling ``indices``. 

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

1078 Determines whether the indices should be viewed as indexing in 

1079 row-major (C-style) or column-major (Fortran-style) order. 

1080 

1081 Returns 

1082 ------- 

1083 unraveled_coords : tuple of ndarray 

1084 Each array in the tuple has the same shape as the ``indices`` 

1085 array. 

1086 

1087 See Also 

1088 -------- 

1089 ravel_multi_index 

1090 

1091 Examples 

1092 -------- 

1093 >>> import numpy as np 

1094 >>> np.unravel_index([22, 41, 37], (7,6)) 

1095 (array([3, 6, 6]), array([4, 5, 1])) 

1096 >>> np.unravel_index([31, 41, 13], (7,6), order='F') 

1097 (array([3, 6, 6]), array([4, 5, 1])) 

1098 

1099 >>> np.unravel_index(1621, (6,7,8,9)) 

1100 (3, 1, 4, 1) 

1101 

1102 """ 

1103 return (indices,) 

1104 

1105 

1106@array_function_from_c_func_and_dispatcher(_multiarray_umath.copyto) 

1107def copyto(dst, src, casting=None, where=None): 

1108 """ 

1109 copyto(dst, src, casting='same_kind', where=True) 

1110 

1111 Copies values from one array to another, broadcasting as necessary. 

1112 

1113 Raises a TypeError if the `casting` rule is violated, and if 

1114 `where` is provided, it selects which elements to copy. 

1115 

1116 Parameters 

1117 ---------- 

1118 dst : ndarray 

1119 The array into which values are copied. 

1120 src : array_like 

1121 The array from which values are copied. 

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

1123 Controls what kind of data casting may occur when copying. 

1124 

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

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

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

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

1129 like float64 to float32, are allowed. 

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

1131 where : array_like of bool, optional 

1132 A boolean array which is broadcasted to match the dimensions 

1133 of `dst`, and selects elements to copy from `src` to `dst` 

1134 wherever it contains the value True. 

1135 

1136 Examples 

1137 -------- 

1138 >>> import numpy as np 

1139 >>> A = np.array([4, 5, 6]) 

1140 >>> B = [1, 2, 3] 

1141 >>> np.copyto(A, B) 

1142 >>> A 

1143 array([1, 2, 3]) 

1144 

1145 >>> A = np.array([[1, 2, 3], [4, 5, 6]]) 

1146 >>> B = [[4, 5, 6], [7, 8, 9]] 

1147 >>> np.copyto(A, B) 

1148 >>> A 

1149 array([[4, 5, 6], 

1150 [7, 8, 9]]) 

1151 

1152 """ 

1153 return (dst, src, where) 

1154 

1155 

1156@array_function_from_c_func_and_dispatcher(_multiarray_umath.putmask) 

1157def putmask(a, /, mask, values): 

1158 """ 

1159 putmask(a, mask, values) 

1160 

1161 Changes elements of an array based on conditional and input values. 

1162 

1163 Sets ``a.flat[n] = values[n]`` for each n where ``mask.flat[n]==True``. 

1164 

1165 If `values` is not the same size as `a` and `mask` then it will repeat. 

1166 This gives behavior different from ``a[mask] = values``. 

1167 

1168 Parameters 

1169 ---------- 

1170 a : ndarray 

1171 Target array. 

1172 mask : array_like 

1173 Boolean mask array. It has to be the same shape as `a`. 

1174 values : array_like 

1175 Values to put into `a` where `mask` is True. If `values` is smaller 

1176 than `a` it will be repeated. 

1177 

1178 See Also 

1179 -------- 

1180 place, put, take, copyto 

1181 

1182 Examples 

1183 -------- 

1184 >>> import numpy as np 

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

1186 >>> np.putmask(x, x>2, x**2) 

1187 >>> x 

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

1189 [ 9, 16, 25]]) 

1190 

1191 If `values` is smaller than `a` it is repeated: 

1192 

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

1194 >>> np.putmask(x, x>1, [-33, -44]) 

1195 >>> x 

1196 array([ 0, 1, -33, -44, -33]) 

1197 

1198 """ 

1199 return (a, mask, values) 

1200 

1201 

1202@array_function_from_c_func_and_dispatcher(_multiarray_umath.packbits) 

1203def packbits(a, axis=None, bitorder='big'): 

1204 """ 

1205 packbits(a, /, axis=None, bitorder='big') 

1206 

1207 Packs the elements of a binary-valued array into bits in a uint8 array. 

1208 

1209 The result is padded to full bytes by inserting zero bits at the end. 

1210 

1211 Parameters 

1212 ---------- 

1213 a : array_like 

1214 An array of integers or booleans whose elements should be packed to 

1215 bits. 

1216 axis : int, optional 

1217 The dimension over which bit-packing is done. 

1218 ``None`` implies packing the flattened array. 

1219 bitorder : {'big', 'little'}, optional 

1220 The order of the input bits. 'big' will mimic bin(val), 

1221 ``[0, 0, 0, 0, 0, 0, 1, 1] => 3 = 0b00000011``, 'little' will 

1222 reverse the order so ``[1, 1, 0, 0, 0, 0, 0, 0] => 3``. 

1223 Defaults to 'big'. 

1224 

1225 Returns 

1226 ------- 

1227 packed : ndarray 

1228 Array of type uint8 whose elements represent bits corresponding to the 

1229 logical (0 or nonzero) value of the input elements. The shape of 

1230 `packed` has the same number of dimensions as the input (unless `axis` 

1231 is None, in which case the output is 1-D). 

1232 

1233 See Also 

1234 -------- 

1235 unpackbits: Unpacks elements of a uint8 array into a binary-valued output 

1236 array. 

1237 

1238 Examples 

1239 -------- 

1240 >>> import numpy as np 

1241 >>> a = np.array([[[1,0,1], 

1242 ... [0,1,0]], 

1243 ... [[1,1,0], 

1244 ... [0,0,1]]]) 

1245 >>> b = np.packbits(a, axis=-1) 

1246 >>> b 

1247 array([[[160], 

1248 [ 64]], 

1249 [[192], 

1250 [ 32]]], dtype=uint8) 

1251 

1252 Note that in binary 160 = 1010 0000, 64 = 0100 0000, 192 = 1100 0000, 

1253 and 32 = 0010 0000. 

1254 

1255 """ 

1256 return (a,) 

1257 

1258 

1259@array_function_from_c_func_and_dispatcher(_multiarray_umath.unpackbits) 

1260def unpackbits(a, axis=None, count=None, bitorder='big'): 

1261 """ 

1262 unpackbits(a, /, axis=None, count=None, bitorder='big') 

1263 

1264 Unpacks elements of a uint8 array into a binary-valued output array. 

1265 

1266 Each element of `a` represents a bit-field that should be unpacked 

1267 into a binary-valued output array. The shape of the output array is 

1268 either 1-D (if `axis` is ``None``) or the same shape as the input 

1269 array with unpacking done along the axis specified. 

1270 

1271 Parameters 

1272 ---------- 

1273 a : ndarray, uint8 type 

1274 Input array. 

1275 axis : int, optional 

1276 The dimension over which bit-unpacking is done. 

1277 ``None`` implies unpacking the flattened array. 

1278 count : int or None, optional 

1279 The number of elements to unpack along `axis`, provided as a way 

1280 of undoing the effect of packing a size that is not a multiple 

1281 of eight. A non-negative number means to only unpack `count` 

1282 bits. A negative number means to trim off that many bits from 

1283 the end. ``None`` means to unpack the entire array (the 

1284 default). Counts larger than the available number of bits will 

1285 add zero padding to the output. Negative counts must not 

1286 exceed the available number of bits. 

1287 bitorder : {'big', 'little'}, optional 

1288 The order of the returned bits. 'big' will mimic bin(val), 

1289 ``3 = 0b00000011 => [0, 0, 0, 0, 0, 0, 1, 1]``, 'little' will reverse 

1290 the order to ``[1, 1, 0, 0, 0, 0, 0, 0]``. 

1291 Defaults to 'big'. 

1292 

1293 Returns 

1294 ------- 

1295 unpacked : ndarray, uint8 type 

1296 The elements are binary-valued (0 or 1). 

1297 

1298 See Also 

1299 -------- 

1300 packbits : Packs the elements of a binary-valued array into bits in 

1301 a uint8 array. 

1302 

1303 Examples 

1304 -------- 

1305 >>> import numpy as np 

1306 >>> a = np.array([[2], [7], [23]], dtype=np.uint8) 

1307 >>> a 

1308 array([[ 2], 

1309 [ 7], 

1310 [23]], dtype=uint8) 

1311 >>> b = np.unpackbits(a, axis=1) 

1312 >>> b 

1313 array([[0, 0, 0, 0, 0, 0, 1, 0], 

1314 [0, 0, 0, 0, 0, 1, 1, 1], 

1315 [0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8) 

1316 >>> c = np.unpackbits(a, axis=1, count=-3) 

1317 >>> c 

1318 array([[0, 0, 0, 0, 0], 

1319 [0, 0, 0, 0, 0], 

1320 [0, 0, 0, 1, 0]], dtype=uint8) 

1321 

1322 >>> p = np.packbits(b, axis=0) 

1323 >>> np.unpackbits(p, axis=0) 

1324 array([[0, 0, 0, 0, 0, 0, 1, 0], 

1325 [0, 0, 0, 0, 0, 1, 1, 1], 

1326 [0, 0, 0, 1, 0, 1, 1, 1], 

1327 [0, 0, 0, 0, 0, 0, 0, 0], 

1328 [0, 0, 0, 0, 0, 0, 0, 0], 

1329 [0, 0, 0, 0, 0, 0, 0, 0], 

1330 [0, 0, 0, 0, 0, 0, 0, 0], 

1331 [0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) 

1332 >>> np.array_equal(b, np.unpackbits(p, axis=0, count=b.shape[0])) 

1333 True 

1334 

1335 """ 

1336 return (a,) 

1337 

1338 

1339@array_function_from_c_func_and_dispatcher(_multiarray_umath.shares_memory) 

1340def shares_memory(a, b, max_work=None): 

1341 """ 

1342 shares_memory(a, b, /, max_work=None) 

1343 

1344 Determine if two arrays share memory. 

1345 

1346 .. warning:: 

1347 

1348 This function can be exponentially slow for some inputs, unless 

1349 `max_work` is set to zero or a positive integer. 

1350 If in doubt, use `numpy.may_share_memory` instead. 

1351 

1352 Parameters 

1353 ---------- 

1354 a, b : ndarray 

1355 Input arrays 

1356 max_work : int, optional 

1357 Effort to spend on solving the overlap problem (maximum number 

1358 of candidate solutions to consider). The following special 

1359 values are recognized: 

1360 

1361 max_work=-1 (default) 

1362 The problem is solved exactly. In this case, the function returns 

1363 True only if there is an element shared between the arrays. Finding 

1364 the exact solution may take extremely long in some cases. 

1365 max_work=0 

1366 Only the memory bounds of a and b are checked. 

1367 This is equivalent to using ``may_share_memory()``. 

1368 

1369 Raises 

1370 ------ 

1371 numpy.exceptions.TooHardError 

1372 Exceeded max_work. 

1373 

1374 Returns 

1375 ------- 

1376 out : bool 

1377 

1378 See Also 

1379 -------- 

1380 may_share_memory 

1381 

1382 Examples 

1383 -------- 

1384 >>> import numpy as np 

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

1386 >>> np.shares_memory(x, np.array([5, 6, 7])) 

1387 False 

1388 >>> np.shares_memory(x[::2], x) 

1389 True 

1390 >>> np.shares_memory(x[::2], x[1::2]) 

1391 False 

1392 

1393 Checking whether two arrays share memory is NP-complete, and 

1394 runtime may increase exponentially in the number of 

1395 dimensions. Hence, `max_work` should generally be set to a finite 

1396 number, as it is possible to construct examples that take 

1397 extremely long to run: 

1398 

1399 >>> from numpy.lib.stride_tricks import as_strided 

1400 >>> x = np.zeros([192163377], dtype=np.int8) 

1401 >>> x1 = as_strided( 

1402 ... x, strides=(36674, 61119, 85569), shape=(1049, 1049, 1049)) 

1403 >>> x2 = as_strided( 

1404 ... x[64023025:], strides=(12223, 12224, 1), shape=(1049, 1049, 1)) 

1405 >>> np.shares_memory(x1, x2, max_work=1000) 

1406 Traceback (most recent call last): 

1407 ... 

1408 numpy.exceptions.TooHardError: Exceeded max_work 

1409 

1410 Running ``np.shares_memory(x1, x2)`` without `max_work` set takes 

1411 around 1 minute for this case. It is possible to find problems 

1412 that take still significantly longer. 

1413 

1414 """ 

1415 return (a, b) 

1416 

1417 

1418@array_function_from_c_func_and_dispatcher(_multiarray_umath.may_share_memory) 

1419def may_share_memory(a, b, max_work=None): 

1420 """ 

1421 may_share_memory(a, b, /, max_work=None) 

1422 

1423 Determine if two arrays might share memory 

1424 

1425 A return of True does not necessarily mean that the two arrays 

1426 share any element. It just means that they *might*. 

1427 

1428 Only the memory bounds of a and b are checked by default. 

1429 

1430 Parameters 

1431 ---------- 

1432 a, b : ndarray 

1433 Input arrays 

1434 max_work : int, optional 

1435 Effort to spend on solving the overlap problem. See 

1436 `shares_memory` for details. Default for ``may_share_memory`` 

1437 is to do a bounds check. 

1438 

1439 Returns 

1440 ------- 

1441 out : bool 

1442 

1443 See Also 

1444 -------- 

1445 shares_memory 

1446 

1447 Examples 

1448 -------- 

1449 >>> import numpy as np 

1450 >>> np.may_share_memory(np.array([1,2]), np.array([5,8,9])) 

1451 False 

1452 >>> x = np.zeros([3, 4]) 

1453 >>> np.may_share_memory(x[:,0], x[:,1]) 

1454 True 

1455 

1456 """ 

1457 return (a, b) 

1458 

1459 

1460@array_function_from_c_func_and_dispatcher(_multiarray_umath.is_busday) 

1461def is_busday(dates, weekmask=None, holidays=None, busdaycal=None, out=None): 

1462 """ 

1463 is_busday( 

1464 dates, 

1465 weekmask='1111100', 

1466 holidays=None, 

1467 busdaycal=None, 

1468 out=None 

1469 ) 

1470 

1471 Calculates which of the given dates are valid days, and which are not. 

1472 

1473 Parameters 

1474 ---------- 

1475 dates : array_like of datetime64[D] 

1476 The array of dates to process. 

1477 weekmask : str or array_like of bool, optional 

1478 A seven-element array indicating which of Monday through Sunday are 

1479 valid days. May be specified as a length-seven list or array, like 

1480 [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string 

1481 like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for 

1482 weekdays, optionally separated by white space. Valid abbreviations 

1483 are: Mon Tue Wed Thu Fri Sat Sun 

1484 holidays : array_like of datetime64[D], optional 

1485 An array of dates to consider as invalid dates. They may be 

1486 specified in any order, and NaT (not-a-time) dates are ignored. 

1487 This list is saved in a normalized form that is suited for 

1488 fast calculations of valid days. 

1489 busdaycal : busdaycalendar, optional 

1490 A `busdaycalendar` object which specifies the valid days. If this 

1491 parameter is provided, neither weekmask nor holidays may be 

1492 provided. 

1493 out : array of bool, optional 

1494 If provided, this array is filled with the result. 

1495 

1496 Returns 

1497 ------- 

1498 out : array of bool 

1499 An array with the same shape as ``dates``, containing True for 

1500 each valid day, and False for each invalid day. 

1501 

1502 See Also 

1503 -------- 

1504 busdaycalendar : An object that specifies a custom set of valid days. 

1505 busday_offset : Applies an offset counted in valid days. 

1506 busday_count : Counts how many valid days are in a half-open date range. 

1507 

1508 Examples 

1509 -------- 

1510 >>> import numpy as np 

1511 >>> # The weekdays are Friday, Saturday, and Monday 

1512 ... np.is_busday(['2011-07-01', '2011-07-02', '2011-07-18'], 

1513 ... holidays=['2011-07-01', '2011-07-04', '2011-07-17']) 

1514 array([False, False, True]) 

1515 """ 

1516 return (dates, weekmask, holidays, out) 

1517 

1518 

1519@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_offset) 

1520def busday_offset(dates, offsets, roll=None, weekmask=None, holidays=None, 

1521 busdaycal=None, out=None): 

1522 """ 

1523 busday_offset( 

1524 dates, 

1525 offsets, 

1526 roll='raise', 

1527 weekmask='1111100', 

1528 holidays=None, 

1529 busdaycal=None, 

1530 out=None 

1531 ) 

1532 

1533 First adjusts the date to fall on a valid day according to 

1534 the ``roll`` rule, then applies offsets to the given dates 

1535 counted in valid days. 

1536 

1537 Parameters 

1538 ---------- 

1539 dates : array_like of datetime64[D] 

1540 The array of dates to process. 

1541 offsets : array_like of int 

1542 The array of offsets, which is broadcast with ``dates``. 

1543 roll : {'raise', 'nat', 'forward', 'following', 'backward', 'preceding', \ 

1544 'modifiedfollowing', 'modifiedpreceding'}, optional 

1545 How to treat dates that do not fall on a valid day. The default 

1546 is 'raise'. 

1547 

1548 * 'raise' means to raise an exception for an invalid day. 

1549 * 'nat' means to return a NaT (not-a-time) for an invalid day. 

1550 * 'forward' and 'following' mean to take the first valid day 

1551 later in time. 

1552 * 'backward' and 'preceding' mean to take the first valid day 

1553 earlier in time. 

1554 * 'modifiedfollowing' means to take the first valid day 

1555 later in time unless it is across a Month boundary, in which 

1556 case to take the first valid day earlier in time. 

1557 * 'modifiedpreceding' means to take the first valid day 

1558 earlier in time unless it is across a Month boundary, in which 

1559 case to take the first valid day later in time. 

1560 weekmask : str or array_like of bool, optional 

1561 A seven-element array indicating which of Monday through Sunday are 

1562 valid days. May be specified as a length-seven list or array, like 

1563 [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string 

1564 like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for 

1565 weekdays, optionally separated by white space. Valid abbreviations 

1566 are: Mon Tue Wed Thu Fri Sat Sun 

1567 holidays : array_like of datetime64[D], optional 

1568 An array of dates to consider as invalid dates. They may be 

1569 specified in any order, and NaT (not-a-time) dates are ignored. 

1570 This list is saved in a normalized form that is suited for 

1571 fast calculations of valid days. 

1572 busdaycal : busdaycalendar, optional 

1573 A `busdaycalendar` object which specifies the valid days. If this 

1574 parameter is provided, neither weekmask nor holidays may be 

1575 provided. 

1576 out : array of datetime64[D], optional 

1577 If provided, this array is filled with the result. 

1578 

1579 Returns 

1580 ------- 

1581 out : array of datetime64[D] 

1582 An array with a shape from broadcasting ``dates`` and ``offsets`` 

1583 together, containing the dates with offsets applied. 

1584 

1585 See Also 

1586 -------- 

1587 busdaycalendar : An object that specifies a custom set of valid days. 

1588 is_busday : Returns a boolean array indicating valid days. 

1589 busday_count : Counts how many valid days are in a half-open date range. 

1590 

1591 Examples 

1592 -------- 

1593 >>> import numpy as np 

1594 >>> # First business day in October 2011 (not accounting for holidays) 

1595 ... np.busday_offset('2011-10', 0, roll='forward') 

1596 np.datetime64('2011-10-03') 

1597 >>> # Last business day in February 2012 (not accounting for holidays) 

1598 ... np.busday_offset('2012-03', -1, roll='forward') 

1599 np.datetime64('2012-02-29') 

1600 >>> # Third Wednesday in January 2011 

1601 ... np.busday_offset('2011-01', 2, roll='forward', weekmask='Wed') 

1602 np.datetime64('2011-01-19') 

1603 >>> # 2012 Mother's Day in Canada and the U.S. 

1604 ... np.busday_offset('2012-05', 1, roll='forward', weekmask='Sun') 

1605 np.datetime64('2012-05-13') 

1606 

1607 >>> # First business day on or after a date 

1608 ... np.busday_offset('2011-03-20', 0, roll='forward') 

1609 np.datetime64('2011-03-21') 

1610 >>> np.busday_offset('2011-03-22', 0, roll='forward') 

1611 np.datetime64('2011-03-22') 

1612 >>> # First business day after a date 

1613 ... np.busday_offset('2011-03-20', 1, roll='backward') 

1614 np.datetime64('2011-03-21') 

1615 >>> np.busday_offset('2011-03-22', 1, roll='backward') 

1616 np.datetime64('2011-03-23') 

1617 """ 

1618 return (dates, offsets, weekmask, holidays, out) 

1619 

1620 

1621@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_count) 

1622def busday_count(begindates, enddates, weekmask=None, holidays=None, 

1623 busdaycal=None, out=None): 

1624 """ 

1625 busday_count( 

1626 begindates, 

1627 enddates, 

1628 weekmask='1111100', 

1629 holidays=[], 

1630 busdaycal=None, 

1631 out=None 

1632 ) 

1633 

1634 Counts the number of valid days between `begindates` and 

1635 `enddates`, not including the day of `enddates`. 

1636 

1637 If ``enddates`` specifies a date value that is earlier than the 

1638 corresponding ``begindates`` date value, the count will be negative. 

1639 

1640 Parameters 

1641 ---------- 

1642 begindates : array_like of datetime64[D] 

1643 The array of the first dates for counting. 

1644 enddates : array_like of datetime64[D] 

1645 The array of the end dates for counting, which are excluded 

1646 from the count themselves. 

1647 weekmask : str or array_like of bool, optional 

1648 A seven-element array indicating which of Monday through Sunday are 

1649 valid days. May be specified as a length-seven list or array, like 

1650 [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string 

1651 like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for 

1652 weekdays, optionally separated by white space. Valid abbreviations 

1653 are: Mon Tue Wed Thu Fri Sat Sun 

1654 holidays : array_like of datetime64[D], optional 

1655 An array of dates to consider as invalid dates. They may be 

1656 specified in any order, and NaT (not-a-time) dates are ignored. 

1657 This list is saved in a normalized form that is suited for 

1658 fast calculations of valid days. 

1659 busdaycal : busdaycalendar, optional 

1660 A `busdaycalendar` object which specifies the valid days. If this 

1661 parameter is provided, neither weekmask nor holidays may be 

1662 provided. 

1663 out : array of int, optional 

1664 If provided, this array is filled with the result. 

1665 

1666 Returns 

1667 ------- 

1668 out : array of int 

1669 An array with a shape from broadcasting ``begindates`` and ``enddates`` 

1670 together, containing the number of valid days between 

1671 the begin and end dates. 

1672 

1673 See Also 

1674 -------- 

1675 busdaycalendar : An object that specifies a custom set of valid days. 

1676 is_busday : Returns a boolean array indicating valid days. 

1677 busday_offset : Applies an offset counted in valid days. 

1678 

1679 Examples 

1680 -------- 

1681 >>> import numpy as np 

1682 >>> # Number of weekdays in January 2011 

1683 ... np.busday_count('2011-01', '2011-02') 

1684 21 

1685 >>> # Number of weekdays in 2011 

1686 >>> np.busday_count('2011', '2012') 

1687 260 

1688 >>> # Number of Saturdays in 2011 

1689 ... np.busday_count('2011', '2012', weekmask='Sat') 

1690 53 

1691 """ 

1692 return (begindates, enddates, weekmask, holidays, out) 

1693 

1694 

1695@array_function_from_c_func_and_dispatcher( 

1696 _multiarray_umath.datetime_as_string) 

1697def datetime_as_string(arr, unit=None, timezone=None, casting=None): 

1698 """ 

1699 datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind') 

1700 

1701 Convert an array of datetimes into an array of strings. 

1702 

1703 Parameters 

1704 ---------- 

1705 arr : array_like of datetime64 

1706 The array of UTC timestamps to format. 

1707 unit : str 

1708 One of None, 'auto', or 

1709 a :ref:`datetime unit <arrays.dtypes.dateunits>`. 

1710 timezone : {'naive', 'UTC', 'local'} or tzinfo 

1711 Timezone information to use when displaying the datetime. If 'UTC', 

1712 end with a Z to indicate UTC time. If 'local', convert to the local 

1713 timezone first, and suffix with a +-#### timezone offset. If a tzinfo 

1714 object, then do as with 'local', but use the specified timezone. 

1715 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'} 

1716 Casting to allow when changing between datetime units. 

1717 

1718 Returns 

1719 ------- 

1720 str_arr : ndarray 

1721 An array of strings the same shape as `arr`. 

1722 

1723 Examples 

1724 -------- 

1725 >>> import numpy as np 

1726 >>> from zoneinfo import ZoneInfo 

1727 >>> d = np.arange('2002-10-27T04:30', 4*60, 60, dtype='M8[m]') 

1728 >>> d 

1729 array(['2002-10-27T04:30', '2002-10-27T05:30', '2002-10-27T06:30', 

1730 '2002-10-27T07:30'], dtype='datetime64[m]') 

1731 

1732 Setting the timezone to UTC shows the same information, but with a Z suffix 

1733 

1734 >>> np.datetime_as_string(d, timezone='UTC') 

1735 array(['2002-10-27T04:30Z', '2002-10-27T05:30Z', '2002-10-27T06:30Z', 

1736 '2002-10-27T07:30Z'], dtype='<U35') 

1737 

1738 Note that we picked datetimes that cross a DST boundary. Passing in a 

1739 ``ZoneInfo`` object will print the appropriate offset 

1740 

1741 >>> np.datetime_as_string(d, timezone=ZoneInfo('US/Eastern')) 

1742 array(['2002-10-27T00:30-0400', '2002-10-27T01:30-0400', 

1743 '2002-10-27T01:30-0500', '2002-10-27T02:30-0500'], dtype='<U39') 

1744 

1745 Passing in a unit will change the precision 

1746 

1747 >>> np.datetime_as_string(d, unit='h') 

1748 array(['2002-10-27T04', '2002-10-27T05', '2002-10-27T06', '2002-10-27T07'], 

1749 dtype='<U32') 

1750 >>> np.datetime_as_string(d, unit='s') 

1751 array(['2002-10-27T04:30:00', '2002-10-27T05:30:00', '2002-10-27T06:30:00', 

1752 '2002-10-27T07:30:00'], dtype='<U38') 

1753 

1754 'casting' can be used to specify whether precision can be changed 

1755 

1756 >>> np.datetime_as_string(d, unit='h', casting='safe') 

1757 Traceback (most recent call last): 

1758 ... 

1759 TypeError: Cannot create a datetime string as units 'h' from a NumPy 

1760 datetime with units 'm' according to the rule 'safe' 

1761 """ 

1762 return (arr,)