Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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 

10import warnings 

11 

12from . import overrides 

13from . import _multiarray_umath 

14from ._multiarray_umath import * # noqa: F403 

15# These imports are needed for backward compatibility, 

16# do not change them. issue gh-15518 

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

18from ._multiarray_umath import ( 

19 _fastCopyAndTranspose, _flagdict, _insert, _reconstruct, _vec_string, 

20 _ARRAY_API, _monotonicity, _get_ndarray_c_version, _set_madvise_hugepage, 

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', '_fastCopyAndTranspose', 

28 '_flagdict', '_insert', '_reconstruct', '_vec_string', '_monotonicity', 

29 'add_docstring', 'arange', 'array', 'bincount', 'broadcast', 

30 'busday_count', 'busday_offset', 'busdaycalendar', 'can_cast', 

31 'compare_chararrays', 'concatenate', 'copyto', 'correlate', 'correlate2', 

32 'count_nonzero', 'c_einsum', 'datetime_as_string', 'datetime_data', 

33 'digitize', 'dot', 'dragon4_positional', 'dragon4_scientific', 'dtype', 

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

35 'frombuffer', 'fromfile', 'fromiter', 'fromstring', 'inner', 

36 'interp', 'interp_complex', 'is_busday', 'lexsort', 

37 'matmul', 'may_share_memory', 'min_scalar_type', 'ndarray', 'nditer', 

38 'nested_iters', 'normalize_axis_index', 'packbits', 

39 'promote_types', 'putmask', 'ravel_multi_index', 'result_type', 'scalar', 

40 'set_datetimeparse_function', 'set_legacy_print_mode', 'set_numeric_ops', 

41 'set_string_function', 'set_typeDict', 'shares_memory', 'test_interrupt', 

42 'tracemalloc_domain', 'typeinfo', 'unpackbits', 'unravel_index', 'vdot', 

43 'where', 'zeros'] 

44 

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

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

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

48 

49 

50arange.__module__ = 'numpy' 

51array.__module__ = 'numpy' 

52datetime_data.__module__ = 'numpy' 

53empty.__module__ = 'numpy' 

54frombuffer.__module__ = 'numpy' 

55fromfile.__module__ = 'numpy' 

56fromiter.__module__ = 'numpy' 

57frompyfunc.__module__ = 'numpy' 

58fromstring.__module__ = 'numpy' 

59geterrobj.__module__ = 'numpy' 

60may_share_memory.__module__ = 'numpy' 

61nested_iters.__module__ = 'numpy' 

62promote_types.__module__ = 'numpy' 

63set_numeric_ops.__module__ = 'numpy' 

64seterrobj.__module__ = 'numpy' 

65zeros.__module__ = 'numpy' 

66 

67 

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

69# support introspection. 

70array_function_from_c_func_and_dispatcher = functools.partial( 

71 overrides.array_function_from_dispatcher, 

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

73 

74 

75@array_function_from_c_func_and_dispatcher(_multiarray_umath.empty_like) 

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

77 """ 

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

79 

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

81 

82 Parameters 

83 ---------- 

84 prototype : array_like 

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

86 of the returned array. 

87 dtype : data-type, optional 

88 Overrides the data type of the result. 

89 

90 .. versionadded:: 1.6.0 

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

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

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

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

95 as closely as possible. 

96 

97 .. versionadded:: 1.6.0 

98 subok : bool, optional. 

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

100 type of 'a', otherwise it will be a base-class array. Defaults 

101 to True. 

102 shape : int or sequence of ints, optional. 

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

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

105 order='C' is implied. 

106 

107 .. versionadded:: 1.17.0 

108 

109 Returns 

110 ------- 

111 out : ndarray 

112 Array of uninitialized (arbitrary) data with the same 

113 shape and type as `prototype`. 

114 

115 See Also 

116 -------- 

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

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

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

120 empty : Return a new uninitialized array. 

121 

122 Notes 

123 ----- 

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

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

126 the functions that do set the array values. 

127 

128 Examples 

129 -------- 

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

131 >>> np.empty_like(a) 

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

133 [ 0, 0, -1073741821]]) 

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

135 >>> np.empty_like(a) 

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

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

138 

139 """ 

140 return (prototype,) 

141 

142 

143@array_function_from_c_func_and_dispatcher(_multiarray_umath.concatenate) 

144def concatenate(arrays, axis=None, out=None): 

145 """ 

146 concatenate((a1, a2, ...), axis=0, out=None) 

147 

148 Join a sequence of arrays along an existing axis. 

149 

150 Parameters 

151 ---------- 

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

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

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

155 axis : int, optional 

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

157 arrays are flattened before use. Default is 0. 

158 out : ndarray, optional 

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

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

161 out argument were specified. 

162 

163 Returns 

164 ------- 

165 res : ndarray 

166 The concatenated array. 

167 

168 See Also 

169 -------- 

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

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

172 near-equal size. 

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

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

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

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

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

178 block : Assemble arrays from blocks. 

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

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

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

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

183 

184 Notes 

185 ----- 

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

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

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

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

190 array module instead. 

191 

192 Examples 

193 -------- 

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

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

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

197 array([[1, 2], 

198 [3, 4], 

199 [5, 6]]) 

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

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

202 [3, 4, 6]]) 

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

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

205 

206 This function will not preserve masking of MaskedArray inputs. 

207 

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

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

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

211 >>> a 

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

213 mask=[False, True, False], 

214 fill_value=999999) 

215 >>> b 

216 array([2, 3, 4]) 

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

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

219 mask=False, 

220 fill_value=999999) 

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

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

223 mask=[False, True, False, False, False, False], 

224 fill_value=999999) 

225 

226 """ 

227 if out is not None: 

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

229 arrays = list(arrays) 

230 arrays.append(out) 

231 return arrays 

232 

233 

234@array_function_from_c_func_and_dispatcher(_multiarray_umath.inner) 

235def inner(a, b): 

236 """ 

237 inner(a, b) 

238 

239 Inner product of two arrays. 

240 

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

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

243 

244 Parameters 

245 ---------- 

246 a, b : array_like 

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

248 

249 Returns 

250 ------- 

251 out : ndarray 

252 `out.shape = a.shape[:-1] + b.shape[:-1]` 

253 

254 Raises 

255 ------ 

256 ValueError 

257 If the last dimension of `a` and `b` has different size. 

258 

259 See Also 

260 -------- 

261 tensordot : Sum products over arbitrary axes. 

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

263 einsum : Einstein summation convention. 

264 

265 Notes 

266 ----- 

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

268 

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

270 

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

272 

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

274 

275 or explicitly:: 

276 

277 np.inner(a, b)[i0,...,ir-1,j0,...,js-1] 

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

279 

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

281 

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

283 

284 Examples 

285 -------- 

286 Ordinary inner product for vectors: 

287 

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

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

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

291 2 

292 

293 A multidimensional example: 

294 

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

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

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

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

299 [ 86, 110, 134]]) 

300 

301 An example where `b` is a scalar: 

302 

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

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

305 [0., 7.]]) 

306 

307 """ 

308 return (a, b) 

309 

310 

311@array_function_from_c_func_and_dispatcher(_multiarray_umath.where) 

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

313 """ 

314 where(condition, [x, y]) 

315 

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

317 

318 .. note:: 

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

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

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

322 documentation covers only the case where all three arguments are 

323 provided. 

324 

325 Parameters 

326 ---------- 

327 condition : array_like, bool 

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

329 x, y : array_like 

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

331 broadcastable to some shape. 

332 

333 Returns 

334 ------- 

335 out : ndarray 

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

337 from `y` elsewhere. 

338 

339 See Also 

340 -------- 

341 choose 

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

343 

344 Notes 

345 ----- 

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

347 

348 [xv if c else yv 

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

350 

351 Examples 

352 -------- 

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

354 >>> a 

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

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

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

358 

359 This can be used on multidimensional arrays too: 

360 

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

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

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

364 array([[1, 8], 

365 [3, 4]]) 

366 

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

368 

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

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

371 array([[10, 0, 0, 0], 

372 [10, 11, 1, 1], 

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

374 

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

376 ... [0, 2, 4], 

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

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

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

380 [ 0, 2, -1], 

381 [ 0, 3, -1]]) 

382 """ 

383 return (condition, x, y) 

384 

385 

386@array_function_from_c_func_and_dispatcher(_multiarray_umath.lexsort) 

387def lexsort(keys, axis=None): 

388 """ 

389 lexsort(keys, axis=-1) 

390 

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

392 

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

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

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

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

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

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

399 for the keys argument, it's rows are interpreted as the sorting keys and 

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

401 

402 Parameters 

403 ---------- 

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

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

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

407 axis : int, optional 

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

409 

410 Returns 

411 ------- 

412 indices : (N,) ndarray of ints 

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

414 

415 See Also 

416 -------- 

417 argsort : Indirect sort. 

418 ndarray.sort : In-place sort. 

419 sort : Return a sorted copy of an array. 

420 

421 Examples 

422 -------- 

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

424 

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

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

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

428 >>> ind 

429 array([1, 2, 0]) 

430 

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

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

433 

434 Sort two columns of numbers: 

435 

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

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

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

439 >>> ind 

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

441 

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

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

444 

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

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

447 

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

449 

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

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

452 

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

454 

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

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

457 

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

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

460 

461 """ 

462 if isinstance(keys, tuple): 

463 return keys 

464 else: 

465 return (keys,) 

466 

467 

468@array_function_from_c_func_and_dispatcher(_multiarray_umath.can_cast) 

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

470 """ 

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

472 

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

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

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

476 to an integer. 

477 

478 Parameters 

479 ---------- 

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

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

482 to : dtype or dtype specifier 

483 Data type to cast to. 

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

485 Controls what kind of data casting may occur. 

486 

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

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

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

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

491 like float64 to float32, are allowed. 

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

493 

494 Returns 

495 ------- 

496 out : bool 

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

498 

499 Notes 

500 ----- 

501 .. versionchanged:: 1.17.0 

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

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

504 casting from multiple fields is not. 

505 

506 .. versionchanged:: 1.9.0 

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

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

509 integer/float value converted. 

510 

511 See also 

512 -------- 

513 dtype, result_type 

514 

515 Examples 

516 -------- 

517 Basic examples 

518 

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

520 True 

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

522 True 

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

524 False 

525 

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

527 True 

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

529 False 

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

531 False 

532 

533 Casting scalars 

534 

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

536 True 

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

538 False 

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

540 True 

541 

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

543 False 

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

545 True 

546 

547 Array scalar checks the value, array does not 

548 

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

550 True 

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

552 False 

553 

554 Using the casting rules 

555 

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

557 True 

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

559 False 

560 

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

562 True 

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

564 False 

565 

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

567 True 

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

569 False 

570 

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

572 True 

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

574 False 

575 

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

577 True 

578 

579 """ 

580 return (from_,) 

581 

582 

583@array_function_from_c_func_and_dispatcher(_multiarray_umath.min_scalar_type) 

584def min_scalar_type(a): 

585 """ 

586 min_scalar_type(a) 

587 

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

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

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

591 

592 Floating point values are not demoted to integers, 

593 and complex values are not demoted to floats. 

594 

595 Parameters 

596 ---------- 

597 a : scalar or array_like 

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

599 

600 Returns 

601 ------- 

602 out : dtype 

603 The minimal data type. 

604 

605 Notes 

606 ----- 

607 .. versionadded:: 1.6.0 

608 

609 See Also 

610 -------- 

611 result_type, promote_types, dtype, can_cast 

612 

613 Examples 

614 -------- 

615 >>> np.min_scalar_type(10) 

616 dtype('uint8') 

617 

618 >>> np.min_scalar_type(-260) 

619 dtype('int16') 

620 

621 >>> np.min_scalar_type(3.1) 

622 dtype('float16') 

623 

624 >>> np.min_scalar_type(1e50) 

625 dtype('float64') 

626 

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

628 dtype('float64') 

629 

630 """ 

631 return (a,) 

632 

633 

634@array_function_from_c_func_and_dispatcher(_multiarray_umath.result_type) 

635def result_type(*arrays_and_dtypes): 

636 """ 

637 result_type(*arrays_and_dtypes) 

638 

639 Returns the type that results from applying the NumPy 

640 type promotion rules to the arguments. 

641 

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

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

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

645 of the scalar is taken into account. 

646 

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

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

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

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

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

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

653 

654 Parameters 

655 ---------- 

656 arrays_and_dtypes : list of arrays and dtypes 

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

658 

659 Returns 

660 ------- 

661 out : dtype 

662 The result type. 

663 

664 See also 

665 -------- 

666 dtype, promote_types, min_scalar_type, can_cast 

667 

668 Notes 

669 ----- 

670 .. versionadded:: 1.6.0 

671 

672 The specific algorithm used is as follows. 

673 

674 Categories are determined by first checking which of boolean, 

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

676 kind of all the arrays and the scalars are. 

677 

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

679 is higher than the maximum category of the arrays, 

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

681 to produce the return value. 

682 

683 Otherwise, `min_scalar_type` is called on each array, and 

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

685 to produce the return value. 

686 

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

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

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

690 

691 Examples 

692 -------- 

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

694 dtype('int8') 

695 

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

697 dtype('complex128') 

698 

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

700 dtype('float64') 

701 

702 """ 

703 return arrays_and_dtypes 

704 

705 

706@array_function_from_c_func_and_dispatcher(_multiarray_umath.dot) 

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

708 """ 

709 dot(a, b, out=None) 

710 

711 Dot product of two arrays. Specifically, 

712 

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

714 (without complex conjugation). 

715 

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

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

718 

719 - If either `a` or `b` is 0-D (scalar), it is equivalent to :func:`multiply` 

720 and using ``numpy.multiply(a, b)`` or ``a * b`` is preferred. 

721 

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

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

724 

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

726 sum product over the last axis of `a` and the second-to-last axis of `b`:: 

727 

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

729 

730 Parameters 

731 ---------- 

732 a : array_like 

733 First argument. 

734 b : array_like 

735 Second argument. 

736 out : ndarray, optional 

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

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

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

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

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

742 to be flexible. 

743 

744 Returns 

745 ------- 

746 output : ndarray 

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

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

749 an array is returned. 

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

751 

752 Raises 

753 ------ 

754 ValueError 

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

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

757 

758 See Also 

759 -------- 

760 vdot : Complex-conjugating dot product. 

761 tensordot : Sum products over arbitrary axes. 

762 einsum : Einstein summation convention. 

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

764 

765 Examples 

766 -------- 

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

768 12 

769 

770 Neither argument is complex-conjugated: 

771 

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

773 (-13+0j) 

774 

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

776 

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

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

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

780 array([[4, 1], 

781 [2, 2]]) 

782 

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

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

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

786 499128 

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

788 499128 

789 

790 """ 

791 return (a, b, out) 

792 

793 

794@array_function_from_c_func_and_dispatcher(_multiarray_umath.vdot) 

795def vdot(a, b): 

796 """ 

797 vdot(a, b) 

798 

799 Return the dot product of two vectors. 

800 

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

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

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

804 

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

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

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

808 

809 Parameters 

810 ---------- 

811 a : array_like 

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

813 of the dot product. 

814 b : array_like 

815 Second argument to the dot product. 

816 

817 Returns 

818 ------- 

819 output : ndarray 

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

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

822 

823 See Also 

824 -------- 

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

826 first argument. 

827 

828 Examples 

829 -------- 

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

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

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

833 (70-8j) 

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

835 (70+8j) 

836 

837 Note that higher-dimensional arrays are flattened! 

838 

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

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

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

842 30 

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

844 30 

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

846 30 

847 

848 """ 

849 return (a, b) 

850 

851 

852@array_function_from_c_func_and_dispatcher(_multiarray_umath.bincount) 

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

854 """ 

855 bincount(x, weights=None, minlength=0) 

856 

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

858 

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

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

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

862 depending on the contents of `x`). 

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

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

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

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

867 

868 Parameters 

869 ---------- 

870 x : array_like, 1 dimension, nonnegative ints 

871 Input array. 

872 weights : array_like, optional 

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

874 minlength : int, optional 

875 A minimum number of bins for the output array. 

876 

877 .. versionadded:: 1.6.0 

878 

879 Returns 

880 ------- 

881 out : ndarray of ints 

882 The result of binning the input array. 

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

884 

885 Raises 

886 ------ 

887 ValueError 

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

889 values, or if `minlength` is negative. 

890 TypeError 

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

892 

893 See Also 

894 -------- 

895 histogram, digitize, unique 

896 

897 Examples 

898 -------- 

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

900 array([1, 1, 1, 1, 1]) 

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

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

903 

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

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

906 True 

907 

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

909 TypeError is raised: 

910 

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

912 Traceback (most recent call last): 

913 ... 

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

915 according to the rule 'safe' 

916 

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

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

919 

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

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

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

923 array([ 0.3, 0.7, 1.1]) 

924 

925 """ 

926 return (x, weights) 

927 

928 

929@array_function_from_c_func_and_dispatcher(_multiarray_umath.ravel_multi_index) 

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

931 """ 

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

933 

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

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

936 

937 Parameters 

938 ---------- 

939 multi_index : tuple of array_like 

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

941 dims : tuple of ints 

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

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

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

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

946 

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

948 * 'wrap' -- wrap around 

949 * 'clip' -- clip to the range 

950 

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

952 wrap will clip to 0 instead. 

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

954 Determines whether the multi-index should be viewed as 

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

956 (Fortran-style) order. 

957 

958 Returns 

959 ------- 

960 raveled_indices : ndarray 

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

962 of dimensions ``dims``. 

963 

964 See Also 

965 -------- 

966 unravel_index 

967 

968 Notes 

969 ----- 

970 .. versionadded:: 1.6.0 

971 

972 Examples 

973 -------- 

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

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

976 array([22, 41, 37]) 

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

978 array([31, 41, 13]) 

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

980 array([22, 23, 19]) 

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

982 array([12, 13, 13]) 

983 

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

985 1621 

986 """ 

987 return multi_index 

988 

989 

990@array_function_from_c_func_and_dispatcher(_multiarray_umath.unravel_index) 

991def unravel_index(indices, shape=None, order=None, dims=None): 

992 """ 

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

994 

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

996 of coordinate arrays. 

997 

998 Parameters 

999 ---------- 

1000 indices : array_like 

1001 An integer array whose elements are indices into the flattened 

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

1003 this function accepted just one index value. 

1004 shape : tuple of ints 

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

1006 

1007 .. versionchanged:: 1.16.0 

1008 Renamed from ``dims`` to ``shape``. 

1009 

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

1011 Determines whether the indices should be viewed as indexing in 

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

1013 

1014 .. versionadded:: 1.6.0 

1015 

1016 Returns 

1017 ------- 

1018 unraveled_coords : tuple of ndarray 

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

1020 array. 

1021 

1022 See Also 

1023 -------- 

1024 ravel_multi_index 

1025 

1026 Examples 

1027 -------- 

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

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

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

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

1032 

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

1034 (3, 1, 4, 1) 

1035 

1036 """ 

1037 if dims is not None: 

1038 warnings.warn("'shape' argument should be used instead of 'dims'", 

1039 DeprecationWarning, stacklevel=3) 

1040 return (indices,) 

1041 

1042 

1043@array_function_from_c_func_and_dispatcher(_multiarray_umath.copyto) 

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

1045 """ 

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

1047 

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

1049 

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

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

1052 

1053 .. versionadded:: 1.7.0 

1054 

1055 Parameters 

1056 ---------- 

1057 dst : ndarray 

1058 The array into which values are copied. 

1059 src : array_like 

1060 The array from which values are copied. 

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

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

1063 

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

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

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

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

1068 like float64 to float32, are allowed. 

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

1070 where : array_like of bool, optional 

1071 A boolean array which is broadcasted to match the dimensions 

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

1073 wherever it contains the value True. 

1074 """ 

1075 return (dst, src, where) 

1076 

1077 

1078@array_function_from_c_func_and_dispatcher(_multiarray_umath.putmask) 

1079def putmask(a, mask, values): 

1080 """ 

1081 putmask(a, mask, values) 

1082 

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

1084 

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

1086 

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

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

1089 

1090 Parameters 

1091 ---------- 

1092 a : array_like 

1093 Target array. 

1094 mask : array_like 

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

1096 values : array_like 

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

1098 than `a` it will be repeated. 

1099 

1100 See Also 

1101 -------- 

1102 place, put, take, copyto 

1103 

1104 Examples 

1105 -------- 

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

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

1108 >>> x 

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

1110 [ 9, 16, 25]]) 

1111 

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

1113 

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

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

1116 >>> x 

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

1118 

1119 """ 

1120 return (a, mask, values) 

1121 

1122 

1123@array_function_from_c_func_and_dispatcher(_multiarray_umath.packbits) 

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

1125 """ 

1126 packbits(a, axis=None, bitorder='big') 

1127 

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

1129 

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

1131 

1132 Parameters 

1133 ---------- 

1134 a : array_like 

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

1136 bits. 

1137 axis : int, optional 

1138 The dimension over which bit-packing is done. 

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

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

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

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

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

1144 Defaults to 'big'. 

1145 

1146 .. versionadded:: 1.17.0 

1147 

1148 Returns 

1149 ------- 

1150 packed : ndarray 

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

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

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

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

1155 

1156 See Also 

1157 -------- 

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

1159 array. 

1160 

1161 Examples 

1162 -------- 

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

1164 ... [0,1,0]], 

1165 ... [[1,1,0], 

1166 ... [0,0,1]]]) 

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

1168 >>> b 

1169 array([[[160], 

1170 [ 64]], 

1171 [[192], 

1172 [ 32]]], dtype=uint8) 

1173 

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

1175 and 32 = 0010 0000. 

1176 

1177 """ 

1178 return (a,) 

1179 

1180 

1181@array_function_from_c_func_and_dispatcher(_multiarray_umath.unpackbits) 

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

1183 """ 

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

1185 

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

1187 

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

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

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

1191 array with unpacking done along the axis specified. 

1192 

1193 Parameters 

1194 ---------- 

1195 a : ndarray, uint8 type 

1196 Input array. 

1197 axis : int, optional 

1198 The dimension over which bit-unpacking is done. 

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

1200 count : int or None, optional 

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

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

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

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

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

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

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

1208 exceed the available number of bits. 

1209 

1210 .. versionadded:: 1.17.0 

1211 

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

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

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

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

1216 Defaults to 'big'. 

1217 

1218 .. versionadded:: 1.17.0 

1219 

1220 Returns 

1221 ------- 

1222 unpacked : ndarray, uint8 type 

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

1224 

1225 See Also 

1226 -------- 

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

1228 a uint8 array. 

1229 

1230 Examples 

1231 -------- 

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

1233 >>> a 

1234 array([[ 2], 

1235 [ 7], 

1236 [23]], dtype=uint8) 

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

1238 >>> b 

1239 array([[0, 0, 0, 0, 0, 0, 1, 0], 

1240 [0, 0, 0, 0, 0, 1, 1, 1], 

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

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

1243 >>> c 

1244 array([[0, 0, 0, 0, 0], 

1245 [0, 0, 0, 0, 0], 

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

1247 

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

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

1250 array([[0, 0, 0, 0, 0, 0, 1, 0], 

1251 [0, 0, 0, 0, 0, 1, 1, 1], 

1252 [0, 0, 0, 1, 0, 1, 1, 1], 

1253 [0, 0, 0, 0, 0, 0, 0, 0], 

1254 [0, 0, 0, 0, 0, 0, 0, 0], 

1255 [0, 0, 0, 0, 0, 0, 0, 0], 

1256 [0, 0, 0, 0, 0, 0, 0, 0], 

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

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

1259 True 

1260 

1261 """ 

1262 return (a,) 

1263 

1264 

1265@array_function_from_c_func_and_dispatcher(_multiarray_umath.shares_memory) 

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

1267 """ 

1268 shares_memory(a, b, max_work=None) 

1269 

1270 Determine if two arrays share memory. 

1271 

1272 .. warning:: 

1273 

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

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

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

1277 

1278 Parameters 

1279 ---------- 

1280 a, b : ndarray 

1281 Input arrays 

1282 max_work : int, optional 

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

1284 of candidate solutions to consider). The following special 

1285 values are recognized: 

1286 

1287 max_work=MAY_SHARE_EXACT (default) 

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

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

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

1291 max_work=MAY_SHARE_BOUNDS 

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

1293 

1294 Raises 

1295 ------ 

1296 numpy.TooHardError 

1297 Exceeded max_work. 

1298 

1299 Returns 

1300 ------- 

1301 out : bool 

1302 

1303 See Also 

1304 -------- 

1305 may_share_memory 

1306 

1307 Examples 

1308 -------- 

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

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

1311 False 

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

1313 True 

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

1315 False 

1316 

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

1318 runtime may increase exponentially in the number of 

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

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

1321 extremely long to run: 

1322 

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

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

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

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

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

1328 Traceback (most recent call last): 

1329 ... 

1330 numpy.TooHardError: Exceeded max_work 

1331 

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

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

1334 that take still significantly longer. 

1335 

1336 """ 

1337 return (a, b) 

1338 

1339 

1340@array_function_from_c_func_and_dispatcher(_multiarray_umath.may_share_memory) 

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

1342 """ 

1343 may_share_memory(a, b, max_work=None) 

1344 

1345 Determine if two arrays might share memory 

1346 

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

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

1349 

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

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. See 

1358 `shares_memory` for details. Default for ``may_share_memory`` 

1359 is to do a bounds check. 

1360 

1361 Returns 

1362 ------- 

1363 out : bool 

1364 

1365 See Also 

1366 -------- 

1367 shares_memory 

1368 

1369 Examples 

1370 -------- 

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

1372 False 

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

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

1375 True 

1376 

1377 """ 

1378 return (a, b) 

1379 

1380 

1381@array_function_from_c_func_and_dispatcher(_multiarray_umath.is_busday) 

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

1383 """ 

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

1385 

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

1387 

1388 .. versionadded:: 1.7.0 

1389 

1390 Parameters 

1391 ---------- 

1392 dates : array_like of datetime64[D] 

1393 The array of dates to process. 

1394 weekmask : str or array_like of bool, optional 

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

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

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

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

1399 weekdays, optionally separated by white space. Valid abbreviations 

1400 are: Mon Tue Wed Thu Fri Sat Sun 

1401 holidays : array_like of datetime64[D], optional 

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

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

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

1405 fast calculations of valid days. 

1406 busdaycal : busdaycalendar, optional 

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

1408 parameter is provided, neither weekmask nor holidays may be 

1409 provided. 

1410 out : array of bool, optional 

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

1412 

1413 Returns 

1414 ------- 

1415 out : array of bool 

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

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

1418 

1419 See Also 

1420 -------- 

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

1422 busday_offset : Applies an offset counted in valid days. 

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

1424 

1425 Examples 

1426 -------- 

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

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

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

1430 array([False, False, True]) 

1431 """ 

1432 return (dates, weekmask, holidays, out) 

1433 

1434 

1435@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_offset) 

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

1437 busdaycal=None, out=None): 

1438 """ 

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

1440 

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

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

1443 counted in valid days. 

1444 

1445 .. versionadded:: 1.7.0 

1446 

1447 Parameters 

1448 ---------- 

1449 dates : array_like of datetime64[D] 

1450 The array of dates to process. 

1451 offsets : array_like of int 

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

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

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

1455 is 'raise'. 

1456 

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

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

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

1460 later in time. 

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

1462 earlier in time. 

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

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

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

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

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

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

1469 weekmask : str or array_like of bool, optional 

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

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

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

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

1474 weekdays, optionally separated by white space. Valid abbreviations 

1475 are: Mon Tue Wed Thu Fri Sat Sun 

1476 holidays : array_like of datetime64[D], optional 

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

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

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

1480 fast calculations of valid days. 

1481 busdaycal : busdaycalendar, optional 

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

1483 parameter is provided, neither weekmask nor holidays may be 

1484 provided. 

1485 out : array of datetime64[D], optional 

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

1487 

1488 Returns 

1489 ------- 

1490 out : array of datetime64[D] 

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

1492 together, containing the dates with offsets applied. 

1493 

1494 See Also 

1495 -------- 

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

1497 is_busday : Returns a boolean array indicating valid days. 

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

1499 

1500 Examples 

1501 -------- 

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

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

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

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

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

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

1508 >>> # Third Wednesday in January 2011 

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

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

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

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

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

1514 

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

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

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

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

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

1520 >>> # First business day after a date 

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

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

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

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

1525 """ 

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

1527 

1528 

1529@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_count) 

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

1531 busdaycal=None, out=None): 

1532 """ 

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

1534 

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

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

1537 

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

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

1540 

1541 .. versionadded:: 1.7.0 

1542 

1543 Parameters 

1544 ---------- 

1545 begindates : array_like of datetime64[D] 

1546 The array of the first dates for counting. 

1547 enddates : array_like of datetime64[D] 

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

1549 from the count themselves. 

1550 weekmask : str or array_like of bool, optional 

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

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

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

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

1555 weekdays, optionally separated by white space. Valid abbreviations 

1556 are: Mon Tue Wed Thu Fri Sat Sun 

1557 holidays : array_like of datetime64[D], optional 

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

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

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

1561 fast calculations of valid days. 

1562 busdaycal : busdaycalendar, optional 

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

1564 parameter is provided, neither weekmask nor holidays may be 

1565 provided. 

1566 out : array of int, optional 

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

1568 

1569 Returns 

1570 ------- 

1571 out : array of int 

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

1573 together, containing the number of valid days between 

1574 the begin and end dates. 

1575 

1576 See Also 

1577 -------- 

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

1579 is_busday : Returns a boolean array indicating valid days. 

1580 busday_offset : Applies an offset counted in valid days. 

1581 

1582 Examples 

1583 -------- 

1584 >>> # Number of weekdays in January 2011 

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

1586 21 

1587 >>> # Number of weekdays in 2011 

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

1589 260 

1590 >>> # Number of Saturdays in 2011 

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

1592 53 

1593 """ 

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

1595 

1596 

1597@array_function_from_c_func_and_dispatcher( 

1598 _multiarray_umath.datetime_as_string) 

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

1600 """ 

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

1602 

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

1604 

1605 Parameters 

1606 ---------- 

1607 arr : array_like of datetime64 

1608 The array of UTC timestamps to format. 

1609 unit : str 

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

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

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

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

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

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

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

1617 Casting to allow when changing between datetime units. 

1618 

1619 Returns 

1620 ------- 

1621 str_arr : ndarray 

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

1623 

1624 Examples 

1625 -------- 

1626 >>> import pytz 

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

1628 >>> d 

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

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

1631 

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

1633 

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

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

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

1637 

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

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

1640 

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

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

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

1644 

1645 Passing in a unit will change the precision 

1646 

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

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

1649 dtype='<U32') 

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

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

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

1653 

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

1655 

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

1657 Traceback (most recent call last): 

1658 ... 

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

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

1661 """ 

1662 return (arr,)