Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/numpy/core/multiarray.py: 81%

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

107 statements  

1""" 

2Create the numpy.core.multiarray namespace for backward compatibility. In v1.16 

3the multiarray and umath c-extension modules were merged into a single 

4_multiarray_umath extension module. So we replicate the old namespace 

5by importing from the extension module. 

6 

7""" 

8 

9import functools 

10from . import overrides 

11from . import _multiarray_umath 

12from ._multiarray_umath import * # noqa: F403 

13# These imports are needed for backward compatibility, 

14# do not change them. issue gh-15518 

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

16from ._multiarray_umath import ( 

17 fastCopyAndTranspose, _flagdict, from_dlpack, _place, _reconstruct, 

18 _vec_string, _ARRAY_API, _monotonicity, _get_ndarray_c_version, 

19 _get_madvise_hugepage, _set_madvise_hugepage, 

20 _get_promotion_state, _set_promotion_state, _using_numpy2_behavior 

21 ) 

22 

23__all__ = [ 

24 '_ARRAY_API', 'ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'DATETIMEUNITS', 

25 'ITEM_HASOBJECT', 'ITEM_IS_POINTER', 'LIST_PICKLE', 'MAXDIMS', 

26 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', 'NEEDS_INIT', 'NEEDS_PYAPI', 

27 'RAISE', 'USE_GETITEM', 'USE_SETITEM', 'WRAP', 

28 '_flagdict', 'from_dlpack', '_place', '_reconstruct', '_vec_string', 

29 '_monotonicity', 'add_docstring', 'arange', 'array', 'asarray', 

30 'asanyarray', 'ascontiguousarray', 'asfortranarray', 'bincount', 

31 'broadcast', 'busday_count', 'busday_offset', 'busdaycalendar', 'can_cast', 

32 'compare_chararrays', 'concatenate', 'copyto', 'correlate', 'correlate2', 

33 'count_nonzero', 'c_einsum', 'datetime_as_string', 'datetime_data', 

34 'dot', 'dragon4_positional', 'dragon4_scientific', 'dtype', 

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

36 'frombuffer', 'fromfile', 'fromiter', 'fromstring', 

37 'get_handler_name', 'get_handler_version', 'inner', 'interp', 

38 'interp_complex', 'is_busday', 'lexsort', 'matmul', 'may_share_memory', 

39 'min_scalar_type', 'ndarray', 'nditer', 'nested_iters', 

40 'normalize_axis_index', 'packbits', 'promote_types', 'putmask', 

41 'ravel_multi_index', 'result_type', 'scalar', 'set_datetimeparse_function', 

42 'set_legacy_print_mode', 'set_numeric_ops', 'set_string_function', 

43 'set_typeDict', 'shares_memory', 'tracemalloc_domain', 'typeinfo', 

44 'unpackbits', 'unravel_index', 'vdot', 'where', 'zeros', 

45 '_get_promotion_state', '_set_promotion_state', '_using_numpy2_behavior'] 

46 

47# For backward compatibility, make sure pickle imports these functions from here 

48_reconstruct.__module__ = 'numpy.core.multiarray' 

49scalar.__module__ = 'numpy.core.multiarray' 

50 

51 

52from_dlpack.__module__ = 'numpy' 

53arange.__module__ = 'numpy' 

54array.__module__ = 'numpy' 

55asarray.__module__ = 'numpy' 

56asanyarray.__module__ = 'numpy' 

57ascontiguousarray.__module__ = 'numpy' 

58asfortranarray.__module__ = 'numpy' 

59datetime_data.__module__ = 'numpy' 

60empty.__module__ = 'numpy' 

61frombuffer.__module__ = 'numpy' 

62fromfile.__module__ = 'numpy' 

63fromiter.__module__ = 'numpy' 

64frompyfunc.__module__ = 'numpy' 

65fromstring.__module__ = 'numpy' 

66geterrobj.__module__ = 'numpy' 

67may_share_memory.__module__ = 'numpy' 

68nested_iters.__module__ = 'numpy' 

69promote_types.__module__ = 'numpy' 

70set_numeric_ops.__module__ = 'numpy' 

71seterrobj.__module__ = 'numpy' 

72zeros.__module__ = 'numpy' 

73_get_promotion_state.__module__ = 'numpy' 

74_set_promotion_state.__module__ = 'numpy' 

75_using_numpy2_behavior.__module__ = 'numpy' 

76 

77 

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

79# support introspection. 

80array_function_from_c_func_and_dispatcher = functools.partial( 

81 overrides.array_function_from_dispatcher, 

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

83 

84 

85@array_function_from_c_func_and_dispatcher(_multiarray_umath.empty_like) 

86def empty_like(prototype, dtype=None, order=None, subok=None, shape=None): 

87 """ 

88 empty_like(prototype, dtype=None, order='K', subok=True, shape=None) 

89 

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

91 

92 Parameters 

93 ---------- 

94 prototype : array_like 

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

96 of the returned array. 

97 dtype : data-type, optional 

98 Overrides the data type of the result. 

99 

100 .. versionadded:: 1.6.0 

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

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

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

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

105 as closely as possible. 

106 

107 .. versionadded:: 1.6.0 

108 subok : bool, optional. 

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

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

111 to True. 

112 shape : int or sequence of ints, optional. 

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

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

115 order='C' is implied. 

116 

117 .. versionadded:: 1.17.0 

118 

119 Returns 

120 ------- 

121 out : ndarray 

122 Array of uninitialized (arbitrary) data with the same 

123 shape and type as `prototype`. 

124 

125 See Also 

126 -------- 

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

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

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

130 empty : Return a new uninitialized array. 

131 

132 Notes 

133 ----- 

134 This function does *not* initialize the returned array; to do that use 

135 `zeros_like` or `ones_like` instead. It may be marginally faster than 

136 the functions that do set the array values. 

137 

138 Examples 

139 -------- 

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

141 >>> np.empty_like(a) 

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

143 [ 0, 0, -1073741821]]) 

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

145 >>> np.empty_like(a) 

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

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

148 

149 """ 

150 return (prototype,) 

151 

152 

153@array_function_from_c_func_and_dispatcher(_multiarray_umath.concatenate) 

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

155 """ 

156 concatenate((a1, a2, ...), axis=0, out=None, dtype=None, casting="same_kind") 

157 

158 Join a sequence of arrays along an existing axis. 

159 

160 Parameters 

161 ---------- 

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

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

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

165 axis : int, optional 

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

167 arrays are flattened before use. Default is 0. 

168 out : ndarray, optional 

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

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

171 out argument were specified. 

172 dtype : str or dtype 

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

174 provided together with `out`. 

175 

176 .. versionadded:: 1.20.0 

177 

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

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

180 

181 .. versionadded:: 1.20.0 

182 

183 Returns 

184 ------- 

185 res : ndarray 

186 The concatenated array. 

187 

188 See Also 

189 -------- 

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

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

192 near-equal size. 

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

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

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

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

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

198 block : Assemble arrays from blocks. 

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

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

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

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

203 

204 Notes 

205 ----- 

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

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

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

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

210 array module instead. 

211 

212 Examples 

213 -------- 

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

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

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

217 array([[1, 2], 

218 [3, 4], 

219 [5, 6]]) 

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

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

222 [3, 4, 6]]) 

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

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

225 

226 This function will not preserve masking of MaskedArray inputs. 

227 

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

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

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

231 >>> a 

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

233 mask=[False, True, False], 

234 fill_value=999999) 

235 >>> b 

236 array([2, 3, 4]) 

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

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

239 mask=False, 

240 fill_value=999999) 

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

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

243 mask=[False, True, False, False, False, False], 

244 fill_value=999999) 

245 

246 """ 

247 if out is not None: 

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

249 arrays = list(arrays) 

250 arrays.append(out) 

251 return arrays 

252 

253 

254@array_function_from_c_func_and_dispatcher(_multiarray_umath.inner) 

255def inner(a, b): 

256 """ 

257 inner(a, b, /) 

258 

259 Inner product of two arrays. 

260 

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

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

263 

264 Parameters 

265 ---------- 

266 a, b : array_like 

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

268 

269 Returns 

270 ------- 

271 out : ndarray 

272 If `a` and `b` are both 

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

274 an array is returned. 

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

276 

277 Raises 

278 ------ 

279 ValueError 

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

281 different sizes. 

282 

283 See Also 

284 -------- 

285 tensordot : Sum products over arbitrary axes. 

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

287 einsum : Einstein summation convention. 

288 

289 Notes 

290 ----- 

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

292 

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

294 

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

296 

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

298 

299 or explicitly:: 

300 

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

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

303 

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

305 

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

307 

308 Examples 

309 -------- 

310 Ordinary inner product for vectors: 

311 

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

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

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

315 2 

316 

317 Some multidimensional examples: 

318 

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

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

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

322 >>> c.shape 

323 (2, 3) 

324 >>> c 

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

326 [ 86, 110, 134]]) 

327 

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

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

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

331 >>> c.shape 

332 (1, 1, 3) 

333 >>> c 

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

335 

336 An example where `b` is a scalar: 

337 

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

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

340 [0., 7.]]) 

341 

342 """ 

343 return (a, b) 

344 

345 

346@array_function_from_c_func_and_dispatcher(_multiarray_umath.where) 

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

348 """ 

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

350 

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

352 

353 .. note:: 

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

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

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

357 documentation covers only the case where all three arguments are 

358 provided. 

359 

360 Parameters 

361 ---------- 

362 condition : array_like, bool 

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

364 x, y : array_like 

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

366 broadcastable to some shape. 

367 

368 Returns 

369 ------- 

370 out : ndarray 

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

372 from `y` elsewhere. 

373 

374 See Also 

375 -------- 

376 choose 

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

378 

379 Notes 

380 ----- 

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

382 

383 [xv if c else yv 

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

385 

386 Examples 

387 -------- 

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

389 >>> a 

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

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

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

393 

394 This can be used on multidimensional arrays too: 

395 

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

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

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

399 array([[1, 8], 

400 [3, 4]]) 

401 

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

403 

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

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

406 array([[10, 0, 0, 0], 

407 [10, 11, 1, 1], 

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

409 

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

411 ... [0, 2, 4], 

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

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

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

415 [ 0, 2, -1], 

416 [ 0, 3, -1]]) 

417 """ 

418 return (condition, x, y) 

419 

420 

421@array_function_from_c_func_and_dispatcher(_multiarray_umath.lexsort) 

422def lexsort(keys, axis=None): 

423 """ 

424 lexsort(keys, axis=-1) 

425 

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

427 

428 Given multiple sorting keys, which can be interpreted as columns in a 

429 spreadsheet, lexsort returns an array of integer indices that describes 

430 the sort order by multiple columns. The last key in the sequence is used 

431 for the primary sort order, the second-to-last key for the secondary sort 

432 order, and so on. The keys argument must be a sequence of objects that 

433 can be converted to arrays of the same shape. If a 2D array is provided 

434 for the keys argument, its rows are interpreted as the sorting keys and 

435 sorting is according to the last row, second last row etc. 

436 

437 Parameters 

438 ---------- 

439 keys : (k, N) array or tuple containing k (N,)-shaped sequences 

440 The `k` different "columns" to be sorted. The last column (or row if 

441 `keys` is a 2D array) is the primary sort key. 

442 axis : int, optional 

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

444 

445 Returns 

446 ------- 

447 indices : (N,) ndarray of ints 

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

449 

450 See Also 

451 -------- 

452 argsort : Indirect sort. 

453 ndarray.sort : In-place sort. 

454 sort : Return a sorted copy of an array. 

455 

456 Examples 

457 -------- 

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

459 

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

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

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

463 >>> ind 

464 array([1, 2, 0]) 

465 

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

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

468 

469 Sort two columns of numbers: 

470 

471 >>> a = [1,5,1,4,3,4,4] # First column 

472 >>> b = [9,4,0,4,0,2,1] # Second column 

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

474 >>> ind 

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

476 

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

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

479 

480 Note that sorting is first according to the elements of ``a``. 

481 Secondary sorting is according to the elements of ``b``. 

482 

483 A normal ``argsort`` would have yielded: 

484 

485 >>> [(a[i],b[i]) for i in np.argsort(a)] 

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

487 

488 Structured arrays are sorted lexically by ``argsort``: 

489 

490 >>> x = np.array([(1,9), (5,4), (1,0), (4,4), (3,0), (4,2), (4,1)], 

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

492 

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

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

495 

496 """ 

497 if isinstance(keys, tuple): 

498 return keys 

499 else: 

500 return (keys,) 

501 

502 

503@array_function_from_c_func_and_dispatcher(_multiarray_umath.can_cast) 

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

505 """ 

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

507 

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

509 casting rule. If from is a scalar or array scalar, also returns 

510 True if the scalar value can be cast without overflow or truncation 

511 to an integer. 

512 

513 Parameters 

514 ---------- 

515 from_ : dtype, dtype specifier, scalar, or array 

516 Data type, scalar, or array to cast from. 

517 to : dtype or dtype specifier 

518 Data type to cast to. 

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

520 Controls what kind of data casting may occur. 

521 

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

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

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

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

526 like float64 to float32, are allowed. 

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

528 

529 Returns 

530 ------- 

531 out : bool 

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

533 

534 Notes 

535 ----- 

536 .. versionchanged:: 1.17.0 

537 Casting between a simple data type and a structured one is possible only 

538 for "unsafe" casting. Casting to multiple fields is allowed, but 

539 casting from multiple fields is not. 

540 

541 .. versionchanged:: 1.9.0 

542 Casting from numeric to string types in 'safe' casting mode requires 

543 that the string dtype length is long enough to store the maximum 

544 integer/float value converted. 

545 

546 See also 

547 -------- 

548 dtype, result_type 

549 

550 Examples 

551 -------- 

552 Basic examples 

553 

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

555 True 

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

557 True 

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

559 False 

560 

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

562 True 

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

564 False 

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

566 False 

567 

568 Casting scalars 

569 

570 >>> np.can_cast(100, 'i1') 

571 True 

572 >>> np.can_cast(150, 'i1') 

573 False 

574 >>> np.can_cast(150, 'u1') 

575 True 

576 

577 >>> np.can_cast(3.5e100, np.float32) 

578 False 

579 >>> np.can_cast(1000.0, np.float32) 

580 True 

581 

582 Array scalar checks the value, array does not 

583 

584 >>> np.can_cast(np.array(1000.0), np.float32) 

585 True 

586 >>> np.can_cast(np.array([1000.0]), np.float32) 

587 False 

588 

589 Using the casting rules 

590 

591 >>> np.can_cast('i8', 'i8', 'no') 

592 True 

593 >>> np.can_cast('<i8', '>i8', 'no') 

594 False 

595 

596 >>> np.can_cast('<i8', '>i8', 'equiv') 

597 True 

598 >>> np.can_cast('<i4', '>i8', 'equiv') 

599 False 

600 

601 >>> np.can_cast('<i4', '>i8', 'safe') 

602 True 

603 >>> np.can_cast('<i8', '>i4', 'safe') 

604 False 

605 

606 >>> np.can_cast('<i8', '>i4', 'same_kind') 

607 True 

608 >>> np.can_cast('<i8', '>u4', 'same_kind') 

609 False 

610 

611 >>> np.can_cast('<i8', '>u4', 'unsafe') 

612 True 

613 

614 """ 

615 return (from_,) 

616 

617 

618@array_function_from_c_func_and_dispatcher(_multiarray_umath.min_scalar_type) 

619def min_scalar_type(a): 

620 """ 

621 min_scalar_type(a, /) 

622 

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

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

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

626 

627 Floating point values are not demoted to integers, 

628 and complex values are not demoted to floats. 

629 

630 Parameters 

631 ---------- 

632 a : scalar or array_like 

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

634 

635 Returns 

636 ------- 

637 out : dtype 

638 The minimal data type. 

639 

640 Notes 

641 ----- 

642 .. versionadded:: 1.6.0 

643 

644 See Also 

645 -------- 

646 result_type, promote_types, dtype, can_cast 

647 

648 Examples 

649 -------- 

650 >>> np.min_scalar_type(10) 

651 dtype('uint8') 

652 

653 >>> np.min_scalar_type(-260) 

654 dtype('int16') 

655 

656 >>> np.min_scalar_type(3.1) 

657 dtype('float16') 

658 

659 >>> np.min_scalar_type(1e50) 

660 dtype('float64') 

661 

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

663 dtype('float64') 

664 

665 """ 

666 return (a,) 

667 

668 

669@array_function_from_c_func_and_dispatcher(_multiarray_umath.result_type) 

670def result_type(*arrays_and_dtypes): 

671 """ 

672 result_type(*arrays_and_dtypes) 

673 

674 Returns the type that results from applying the NumPy 

675 type promotion rules to the arguments. 

676 

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

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

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

680 of the scalar is taken into account. 

681 

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

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

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

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

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

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

688 

689 Parameters 

690 ---------- 

691 arrays_and_dtypes : list of arrays and dtypes 

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

693 

694 Returns 

695 ------- 

696 out : dtype 

697 The result type. 

698 

699 See also 

700 -------- 

701 dtype, promote_types, min_scalar_type, can_cast 

702 

703 Notes 

704 ----- 

705 .. versionadded:: 1.6.0 

706 

707 The specific algorithm used is as follows. 

708 

709 Categories are determined by first checking which of boolean, 

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

711 kind of all the arrays and the scalars are. 

712 

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

714 is higher than the maximum category of the arrays, 

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

716 to produce the return value. 

717 

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

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

720 to produce the return value. 

721 

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

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

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

725 

726 Examples 

727 -------- 

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

729 dtype('int8') 

730 

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

732 dtype('complex128') 

733 

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

735 dtype('float64') 

736 

737 """ 

738 return arrays_and_dtypes 

739 

740 

741@array_function_from_c_func_and_dispatcher(_multiarray_umath.dot) 

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

743 """ 

744 dot(a, b, out=None) 

745 

746 Dot product of two arrays. Specifically, 

747 

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

749 (without complex conjugation). 

750 

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

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

753 

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

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

756 preferred. 

757 

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

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

760 

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

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

763 `b`:: 

764 

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

766 

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

768 

769 Parameters 

770 ---------- 

771 a : array_like 

772 First argument. 

773 b : array_like 

774 Second argument. 

775 out : ndarray, optional 

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

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

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

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

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

781 to be flexible. 

782 

783 Returns 

784 ------- 

785 output : ndarray 

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

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

788 an array is returned. 

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

790 

791 Raises 

792 ------ 

793 ValueError 

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

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

796 

797 See Also 

798 -------- 

799 vdot : Complex-conjugating dot product. 

800 tensordot : Sum products over arbitrary axes. 

801 einsum : Einstein summation convention. 

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

803 linalg.multi_dot : Chained dot product. 

804 

805 Examples 

806 -------- 

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

808 12 

809 

810 Neither argument is complex-conjugated: 

811 

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

813 (-13+0j) 

814 

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

816 

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

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

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

820 array([[4, 1], 

821 [2, 2]]) 

822 

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

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

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

826 499128 

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

828 499128 

829 

830 """ 

831 return (a, b, out) 

832 

833 

834@array_function_from_c_func_and_dispatcher(_multiarray_umath.vdot) 

835def vdot(a, b): 

836 """ 

837 vdot(a, b, /) 

838 

839 Return the dot product of two vectors. 

840 

841 The vdot(`a`, `b`) function handles complex numbers differently than 

842 dot(`a`, `b`). If the first argument is complex the complex conjugate 

843 of the first argument is used for the calculation of the dot product. 

844 

845 Note that `vdot` handles multidimensional arrays differently than `dot`: 

846 it does *not* perform a matrix product, but flattens input arguments 

847 to 1-D vectors first. Consequently, it should only be used for vectors. 

848 

849 Parameters 

850 ---------- 

851 a : array_like 

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

853 of the dot product. 

854 b : array_like 

855 Second argument to the dot product. 

856 

857 Returns 

858 ------- 

859 output : ndarray 

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

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

862 

863 See Also 

864 -------- 

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

866 first argument. 

867 

868 Examples 

869 -------- 

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

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

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

873 (70-8j) 

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

875 (70+8j) 

876 

877 Note that higher-dimensional arrays are flattened! 

878 

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

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

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

882 30 

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

884 30 

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

886 30 

887 

888 """ 

889 return (a, b) 

890 

891 

892@array_function_from_c_func_and_dispatcher(_multiarray_umath.bincount) 

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

894 """ 

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

896 

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

898 

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

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

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

902 depending on the contents of `x`). 

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

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

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

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

907 

908 Parameters 

909 ---------- 

910 x : array_like, 1 dimension, nonnegative ints 

911 Input array. 

912 weights : array_like, optional 

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

914 minlength : int, optional 

915 A minimum number of bins for the output array. 

916 

917 .. versionadded:: 1.6.0 

918 

919 Returns 

920 ------- 

921 out : ndarray of ints 

922 The result of binning the input array. 

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

924 

925 Raises 

926 ------ 

927 ValueError 

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

929 values, or if `minlength` is negative. 

930 TypeError 

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

932 

933 See Also 

934 -------- 

935 histogram, digitize, unique 

936 

937 Examples 

938 -------- 

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

940 array([1, 1, 1, 1, 1]) 

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

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

943 

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

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

946 True 

947 

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

949 TypeError is raised: 

950 

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

952 Traceback (most recent call last): 

953 ... 

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

955 according to the rule 'safe' 

956 

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

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

959 

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

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

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

963 array([ 0.3, 0.7, 1.1]) 

964 

965 """ 

966 return (x, weights) 

967 

968 

969@array_function_from_c_func_and_dispatcher(_multiarray_umath.ravel_multi_index) 

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

971 """ 

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

973 

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

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

976 

977 Parameters 

978 ---------- 

979 multi_index : tuple of array_like 

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

981 dims : tuple of ints 

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

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

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

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

986 

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

988 * 'wrap' -- wrap around 

989 * 'clip' -- clip to the range 

990 

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

992 wrap will clip to 0 instead. 

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

994 Determines whether the multi-index should be viewed as 

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

996 (Fortran-style) order. 

997 

998 Returns 

999 ------- 

1000 raveled_indices : ndarray 

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

1002 of dimensions ``dims``. 

1003 

1004 See Also 

1005 -------- 

1006 unravel_index 

1007 

1008 Notes 

1009 ----- 

1010 .. versionadded:: 1.6.0 

1011 

1012 Examples 

1013 -------- 

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

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

1016 array([22, 41, 37]) 

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

1018 array([31, 41, 13]) 

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

1020 array([22, 23, 19]) 

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

1022 array([12, 13, 13]) 

1023 

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

1025 1621 

1026 """ 

1027 return multi_index 

1028 

1029 

1030@array_function_from_c_func_and_dispatcher(_multiarray_umath.unravel_index) 

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

1032 """ 

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

1034 

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

1036 of coordinate arrays. 

1037 

1038 Parameters 

1039 ---------- 

1040 indices : array_like 

1041 An integer array whose elements are indices into the flattened 

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

1043 this function accepted just one index value. 

1044 shape : tuple of ints 

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

1046 

1047 .. versionchanged:: 1.16.0 

1048 Renamed from ``dims`` to ``shape``. 

1049 

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

1051 Determines whether the indices should be viewed as indexing in 

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

1053 

1054 .. versionadded:: 1.6.0 

1055 

1056 Returns 

1057 ------- 

1058 unraveled_coords : tuple of ndarray 

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

1060 array. 

1061 

1062 See Also 

1063 -------- 

1064 ravel_multi_index 

1065 

1066 Examples 

1067 -------- 

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

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

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

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

1072 

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

1074 (3, 1, 4, 1) 

1075 

1076 """ 

1077 return (indices,) 

1078 

1079 

1080@array_function_from_c_func_and_dispatcher(_multiarray_umath.copyto) 

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

1082 """ 

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

1084 

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

1086 

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

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

1089 

1090 .. versionadded:: 1.7.0 

1091 

1092 Parameters 

1093 ---------- 

1094 dst : ndarray 

1095 The array into which values are copied. 

1096 src : array_like 

1097 The array from which values are copied. 

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

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

1100 

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

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

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

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

1105 like float64 to float32, are allowed. 

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

1107 where : array_like of bool, optional 

1108 A boolean array which is broadcasted to match the dimensions 

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

1110 wherever it contains the value True. 

1111 

1112 Examples 

1113 -------- 

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

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

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

1117 >>> A 

1118 array([1, 2, 3]) 

1119 

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

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

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

1123 >>> A 

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

1125 [7, 8, 9]]) 

1126 

1127 """ 

1128 return (dst, src, where) 

1129 

1130 

1131@array_function_from_c_func_and_dispatcher(_multiarray_umath.putmask) 

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

1133 """ 

1134 putmask(a, mask, values) 

1135 

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

1137 

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

1139 

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

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

1142 

1143 Parameters 

1144 ---------- 

1145 a : ndarray 

1146 Target array. 

1147 mask : array_like 

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

1149 values : array_like 

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

1151 than `a` it will be repeated. 

1152 

1153 See Also 

1154 -------- 

1155 place, put, take, copyto 

1156 

1157 Examples 

1158 -------- 

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

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

1161 >>> x 

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

1163 [ 9, 16, 25]]) 

1164 

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

1166 

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

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

1169 >>> x 

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

1171 

1172 """ 

1173 return (a, mask, values) 

1174 

1175 

1176@array_function_from_c_func_and_dispatcher(_multiarray_umath.packbits) 

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

1178 """ 

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

1180 

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

1182 

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

1184 

1185 Parameters 

1186 ---------- 

1187 a : array_like 

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

1189 bits. 

1190 axis : int, optional 

1191 The dimension over which bit-packing is done. 

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

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

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

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

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

1197 Defaults to 'big'. 

1198 

1199 .. versionadded:: 1.17.0 

1200 

1201 Returns 

1202 ------- 

1203 packed : ndarray 

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

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

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

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

1208 

1209 See Also 

1210 -------- 

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

1212 array. 

1213 

1214 Examples 

1215 -------- 

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

1217 ... [0,1,0]], 

1218 ... [[1,1,0], 

1219 ... [0,0,1]]]) 

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

1221 >>> b 

1222 array([[[160], 

1223 [ 64]], 

1224 [[192], 

1225 [ 32]]], dtype=uint8) 

1226 

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

1228 and 32 = 0010 0000. 

1229 

1230 """ 

1231 return (a,) 

1232 

1233 

1234@array_function_from_c_func_and_dispatcher(_multiarray_umath.unpackbits) 

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

1236 """ 

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

1238 

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

1240 

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

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

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

1244 array with unpacking done along the axis specified. 

1245 

1246 Parameters 

1247 ---------- 

1248 a : ndarray, uint8 type 

1249 Input array. 

1250 axis : int, optional 

1251 The dimension over which bit-unpacking is done. 

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

1253 count : int or None, optional 

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

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

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

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

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

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

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

1261 exceed the available number of bits. 

1262 

1263 .. versionadded:: 1.17.0 

1264 

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

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

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

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

1269 Defaults to 'big'. 

1270 

1271 .. versionadded:: 1.17.0 

1272 

1273 Returns 

1274 ------- 

1275 unpacked : ndarray, uint8 type 

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

1277 

1278 See Also 

1279 -------- 

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

1281 a uint8 array. 

1282 

1283 Examples 

1284 -------- 

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

1286 >>> a 

1287 array([[ 2], 

1288 [ 7], 

1289 [23]], dtype=uint8) 

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

1291 >>> b 

1292 array([[0, 0, 0, 0, 0, 0, 1, 0], 

1293 [0, 0, 0, 0, 0, 1, 1, 1], 

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

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

1296 >>> c 

1297 array([[0, 0, 0, 0, 0], 

1298 [0, 0, 0, 0, 0], 

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

1300 

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

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

1303 array([[0, 0, 0, 0, 0, 0, 1, 0], 

1304 [0, 0, 0, 0, 0, 1, 1, 1], 

1305 [0, 0, 0, 1, 0, 1, 1, 1], 

1306 [0, 0, 0, 0, 0, 0, 0, 0], 

1307 [0, 0, 0, 0, 0, 0, 0, 0], 

1308 [0, 0, 0, 0, 0, 0, 0, 0], 

1309 [0, 0, 0, 0, 0, 0, 0, 0], 

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

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

1312 True 

1313 

1314 """ 

1315 return (a,) 

1316 

1317 

1318@array_function_from_c_func_and_dispatcher(_multiarray_umath.shares_memory) 

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

1320 """ 

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

1322 

1323 Determine if two arrays share memory. 

1324 

1325 .. warning:: 

1326 

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

1328 `max_work` is set to a finite number or ``MAY_SHARE_BOUNDS``. 

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

1330 

1331 Parameters 

1332 ---------- 

1333 a, b : ndarray 

1334 Input arrays 

1335 max_work : int, optional 

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

1337 of candidate solutions to consider). The following special 

1338 values are recognized: 

1339 

1340 max_work=MAY_SHARE_EXACT (default) 

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

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

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

1344 max_work=MAY_SHARE_BOUNDS 

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

1346 

1347 Raises 

1348 ------ 

1349 numpy.exceptions.TooHardError 

1350 Exceeded max_work. 

1351 

1352 Returns 

1353 ------- 

1354 out : bool 

1355 

1356 See Also 

1357 -------- 

1358 may_share_memory 

1359 

1360 Examples 

1361 -------- 

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

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

1364 False 

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

1366 True 

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

1368 False 

1369 

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

1371 runtime may increase exponentially in the number of 

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

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

1374 extremely long to run: 

1375 

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

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

1378 >>> x1 = as_strided(x, strides=(36674, 61119, 85569), shape=(1049, 1049, 1049)) 

1379 >>> x2 = as_strided(x[64023025:], strides=(12223, 12224, 1), shape=(1049, 1049, 1)) 

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

1381 Traceback (most recent call last): 

1382 ... 

1383 numpy.exceptions.TooHardError: Exceeded max_work 

1384 

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

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

1387 that take still significantly longer. 

1388 

1389 """ 

1390 return (a, b) 

1391 

1392 

1393@array_function_from_c_func_and_dispatcher(_multiarray_umath.may_share_memory) 

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

1395 """ 

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

1397 

1398 Determine if two arrays might share memory 

1399 

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

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

1402 

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

1404 

1405 Parameters 

1406 ---------- 

1407 a, b : ndarray 

1408 Input arrays 

1409 max_work : int, optional 

1410 Effort to spend on solving the overlap problem. See 

1411 `shares_memory` for details. Default for ``may_share_memory`` 

1412 is to do a bounds check. 

1413 

1414 Returns 

1415 ------- 

1416 out : bool 

1417 

1418 See Also 

1419 -------- 

1420 shares_memory 

1421 

1422 Examples 

1423 -------- 

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

1425 False 

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

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

1428 True 

1429 

1430 """ 

1431 return (a, b) 

1432 

1433 

1434@array_function_from_c_func_and_dispatcher(_multiarray_umath.is_busday) 

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

1436 """ 

1437 is_busday(dates, weekmask='1111100', holidays=None, busdaycal=None, out=None) 

1438 

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

1440 

1441 .. versionadded:: 1.7.0 

1442 

1443 Parameters 

1444 ---------- 

1445 dates : array_like of datetime64[D] 

1446 The array of dates to process. 

1447 weekmask : str or array_like of bool, optional 

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

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

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

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

1452 weekdays, optionally separated by white space. Valid abbreviations 

1453 are: Mon Tue Wed Thu Fri Sat Sun 

1454 holidays : array_like of datetime64[D], optional 

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

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

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

1458 fast calculations of valid days. 

1459 busdaycal : busdaycalendar, optional 

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

1461 parameter is provided, neither weekmask nor holidays may be 

1462 provided. 

1463 out : array of bool, optional 

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

1465 

1466 Returns 

1467 ------- 

1468 out : array of bool 

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

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

1471 

1472 See Also 

1473 -------- 

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

1475 busday_offset : Applies an offset counted in valid days. 

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

1477 

1478 Examples 

1479 -------- 

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

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

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

1483 array([False, False, True]) 

1484 """ 

1485 return (dates, weekmask, holidays, out) 

1486 

1487 

1488@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_offset) 

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

1490 busdaycal=None, out=None): 

1491 """ 

1492 busday_offset(dates, offsets, roll='raise', weekmask='1111100', holidays=None, busdaycal=None, out=None) 

1493 

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

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

1496 counted in valid days. 

1497 

1498 .. versionadded:: 1.7.0 

1499 

1500 Parameters 

1501 ---------- 

1502 dates : array_like of datetime64[D] 

1503 The array of dates to process. 

1504 offsets : array_like of int 

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

1506 roll : {'raise', 'nat', 'forward', 'following', 'backward', 'preceding', 'modifiedfollowing', 'modifiedpreceding'}, optional 

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

1508 is 'raise'. 

1509 

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

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

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

1513 later in time. 

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

1515 earlier in time. 

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

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

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

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

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

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

1522 weekmask : str or array_like of bool, optional 

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

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

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

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

1527 weekdays, optionally separated by white space. Valid abbreviations 

1528 are: Mon Tue Wed Thu Fri Sat Sun 

1529 holidays : array_like of datetime64[D], optional 

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

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

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

1533 fast calculations of valid days. 

1534 busdaycal : busdaycalendar, optional 

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

1536 parameter is provided, neither weekmask nor holidays may be 

1537 provided. 

1538 out : array of datetime64[D], optional 

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

1540 

1541 Returns 

1542 ------- 

1543 out : array of datetime64[D] 

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

1545 together, containing the dates with offsets applied. 

1546 

1547 See Also 

1548 -------- 

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

1550 is_busday : Returns a boolean array indicating valid days. 

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

1552 

1553 Examples 

1554 -------- 

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

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

1557 numpy.datetime64('2011-10-03') 

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

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

1560 numpy.datetime64('2012-02-29') 

1561 >>> # Third Wednesday in January 2011 

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

1563 numpy.datetime64('2011-01-19') 

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

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

1566 numpy.datetime64('2012-05-13') 

1567 

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

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

1570 numpy.datetime64('2011-03-21') 

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

1572 numpy.datetime64('2011-03-22') 

1573 >>> # First business day after a date 

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

1575 numpy.datetime64('2011-03-21') 

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

1577 numpy.datetime64('2011-03-23') 

1578 """ 

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

1580 

1581 

1582@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_count) 

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

1584 busdaycal=None, out=None): 

1585 """ 

1586 busday_count(begindates, enddates, weekmask='1111100', holidays=[], busdaycal=None, out=None) 

1587 

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

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

1590 

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

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

1593 

1594 .. versionadded:: 1.7.0 

1595 

1596 Parameters 

1597 ---------- 

1598 begindates : array_like of datetime64[D] 

1599 The array of the first dates for counting. 

1600 enddates : array_like of datetime64[D] 

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

1602 from the count themselves. 

1603 weekmask : str or array_like of bool, optional 

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

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

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

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

1608 weekdays, optionally separated by white space. Valid abbreviations 

1609 are: Mon Tue Wed Thu Fri Sat Sun 

1610 holidays : array_like of datetime64[D], optional 

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

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

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

1614 fast calculations of valid days. 

1615 busdaycal : busdaycalendar, optional 

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

1617 parameter is provided, neither weekmask nor holidays may be 

1618 provided. 

1619 out : array of int, optional 

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

1621 

1622 Returns 

1623 ------- 

1624 out : array of int 

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

1626 together, containing the number of valid days between 

1627 the begin and end dates. 

1628 

1629 See Also 

1630 -------- 

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

1632 is_busday : Returns a boolean array indicating valid days. 

1633 busday_offset : Applies an offset counted in valid days. 

1634 

1635 Examples 

1636 -------- 

1637 >>> # Number of weekdays in January 2011 

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

1639 21 

1640 >>> # Number of weekdays in 2011 

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

1642 260 

1643 >>> # Number of Saturdays in 2011 

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

1645 53 

1646 """ 

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

1648 

1649 

1650@array_function_from_c_func_and_dispatcher( 

1651 _multiarray_umath.datetime_as_string) 

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

1653 """ 

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

1655 

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

1657 

1658 Parameters 

1659 ---------- 

1660 arr : array_like of datetime64 

1661 The array of UTC timestamps to format. 

1662 unit : str 

1663 One of None, 'auto', or a :ref:`datetime unit <arrays.dtypes.dateunits>`. 

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

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

1666 with a Z to indicate UTC time. If 'local', convert to the local timezone 

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

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

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

1670 Casting to allow when changing between datetime units. 

1671 

1672 Returns 

1673 ------- 

1674 str_arr : ndarray 

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

1676 

1677 Examples 

1678 -------- 

1679 >>> import pytz 

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

1681 >>> d 

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

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

1684 

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

1686 

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

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

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

1690 

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

1692 ``pytz`` timezone object will print the appropriate offset 

1693 

1694 >>> np.datetime_as_string(d, timezone=pytz.timezone('US/Eastern')) 

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

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

1697 

1698 Passing in a unit will change the precision 

1699 

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

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

1702 dtype='<U32') 

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

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

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

1706 

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

1708 

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

1710 Traceback (most recent call last): 

1711 ... 

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

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

1714 """ 

1715 return (arr,)