0
# Array Creation and Manipulation
1
2
Core NumPy functionality for creating, reshaping, joining, and manipulating N-dimensional arrays. These operations form the foundation of array-based computing in Python.
3
4
## Capabilities
5
6
### Basic Array Creation
7
8
Create arrays from existing data or initialize new arrays with specific patterns.
9
10
```python { .api }
11
def array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0, like=None):
12
"""
13
Create an array from an array-like object.
14
15
Parameters:
16
- object: array_like, sequence to convert to array
17
- dtype: data-type, desired data type
18
- copy: bool, whether to copy the data
19
- order: {'K', 'A', 'C', 'F'}, memory layout
20
- subok: bool, whether to pass through subclasses
21
- ndmin: int, minimum number of dimensions
22
- like: array_like, reference object for array creation
23
24
Returns:
25
ndarray: New array object
26
"""
27
28
def asarray(a, dtype=None, order=None, like=None):
29
"""
30
Convert input to an array.
31
32
Parameters:
33
- a: array_like, input data
34
- dtype: data-type, desired data type
35
- order: {'C', 'F', 'A', 'K'}, memory layout
36
- like: array_like, reference object
37
38
Returns:
39
ndarray: Array interpretation of input
40
"""
41
42
def asanyarray(a, dtype=None, order=None, like=None):
43
"""
44
Convert input to ndarray, preserving subclasses.
45
46
Parameters:
47
- a: array_like, input data
48
- dtype: data-type, desired data type
49
- order: {'C', 'F', 'A', 'K'}, memory layout
50
- like: array_like, reference object
51
52
Returns:
53
ndarray: Array interpretation preserving subclass
54
"""
55
56
def ascontiguousarray(a, dtype=None, like=None):
57
"""
58
Return a contiguous array in memory (C order).
59
60
Parameters:
61
- a: array_like, input array
62
- dtype: data-type, desired data type
63
- like: array_like, reference object
64
65
Returns:
66
ndarray: Contiguous array
67
"""
68
69
def asfortranarray(a, dtype=None, like=None):
70
"""
71
Return an array laid out in Fortran order in memory.
72
73
Parameters:
74
- a: array_like, input array
75
- dtype: data-type, desired data type
76
- like: array_like, reference object
77
78
Returns:
79
ndarray: Fortran-ordered array
80
"""
81
```
82
83
### Array Initialization
84
85
Create arrays filled with specific values or uninitialized arrays of given shapes.
86
87
```python { .api }
88
def empty(shape, dtype=float, order='C', like=None):
89
"""
90
Return a new array of given shape without initializing entries.
91
92
Parameters:
93
- shape: int or tuple of ints, shape of new array
94
- dtype: data-type, desired data type
95
- order: {'C', 'F'}, memory layout
96
- like: array_like, reference object
97
98
Returns:
99
ndarray: Uninitialized array
100
"""
101
102
def zeros(shape, dtype=float, order='C', like=None):
103
"""
104
Return a new array of given shape filled with zeros.
105
106
Parameters:
107
- shape: int or tuple of ints, shape of new array
108
- dtype: data-type, desired data type
109
- order: {'C', 'F'}, memory layout
110
- like: array_like, reference object
111
112
Returns:
113
ndarray: Array of zeros
114
"""
115
116
def ones(shape, dtype=None, order='C', like=None):
117
"""
118
Return a new array of given shape filled with ones.
119
120
Parameters:
121
- shape: int or tuple of ints, shape of new array
122
- dtype: data-type, desired data type
123
- order: {'C', 'F'}, memory layout
124
- like: array_like, reference object
125
126
Returns:
127
ndarray: Array of ones
128
"""
129
130
def full(shape, fill_value, dtype=None, order='C', like=None):
131
"""
132
Return a new array of given shape filled with fill_value.
133
134
Parameters:
135
- shape: int or tuple of ints, shape of new array
136
- fill_value: scalar, fill value
137
- dtype: data-type, desired data type
138
- order: {'C', 'F'}, memory layout
139
- like: array_like, reference object
140
141
Returns:
142
ndarray: Array filled with fill_value
143
"""
144
```
145
146
### Array Creation from Existing Arrays
147
148
Create arrays with the same shape as existing arrays.
149
150
```python { .api }
151
def empty_like(prototype, dtype=None, order='K', subok=True, shape=None):
152
"""
153
Return a new array with the same shape as a given array.
154
155
Parameters:
156
- prototype: array_like, shape and data-type of prototype define these
157
- dtype: data-type, override data type
158
- order: {'C', 'F', 'A', 'K'}, memory layout
159
- subok: bool, return a subarray if True
160
- shape: int or tuple of ints, override shape
161
162
Returns:
163
ndarray: Uninitialized array with same shape as prototype
164
"""
165
166
def zeros_like(a, dtype=None, order='K', subok=True, shape=None):
167
"""
168
Return an array of zeros with the same shape as a given array.
169
170
Parameters:
171
- a: array_like, shape and data-type of a define these
172
- dtype: data-type, override data type
173
- order: {'C', 'F', 'A', 'K'}, memory layout
174
- subok: bool, return a subarray if True
175
- shape: int or tuple of ints, override shape
176
177
Returns:
178
ndarray: Array of zeros with same shape as a
179
"""
180
181
def ones_like(a, dtype=None, order='K', subok=True, shape=None):
182
"""
183
Return an array of ones with the same shape as a given array.
184
185
Parameters:
186
- a: array_like, shape and data-type of a define these
187
- dtype: data-type, override data type
188
- order: {'C', 'F', 'A', 'K'}, memory layout
189
- subok: bool, return a subarray if True
190
- shape: int or tuple of ints, override shape
191
192
Returns:
193
ndarray: Array of ones with same shape as a
194
"""
195
196
def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None):
197
"""
198
Return a full array with the same shape as a given array.
199
200
Parameters:
201
- a: array_like, shape and data-type of a define these
202
- fill_value: scalar, fill value
203
- dtype: data-type, override data type
204
- order: {'C', 'F', 'A', 'K'}, memory layout
205
- subok: bool, return a subarray if True
206
- shape: int or tuple of ints, override shape
207
208
Returns:
209
ndarray: Array filled with fill_value with same shape as a
210
"""
211
```
212
213
### Numerical Ranges
214
215
Create arrays containing sequences of numbers.
216
217
```python { .api }
218
def arange(start, stop=None, step=1, dtype=None, like=None):
219
"""
220
Return evenly spaced values within a given interval.
221
222
Parameters:
223
- start: number, start of interval
224
- stop: number, end of interval (not included)
225
- step: number, spacing between values
226
- dtype: data-type, type of output array
227
- like: array_like, reference object
228
229
Returns:
230
ndarray: Array of evenly spaced values
231
"""
232
233
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0):
234
"""
235
Return evenly spaced numbers over a specified interval.
236
237
Parameters:
238
- start: array_like, starting value of sequence
239
- stop: array_like, end value of sequence
240
- num: int, number of samples to generate
241
- endpoint: bool, whether to include stop in samples
242
- retstep: bool, whether to return spacing between samples
243
- dtype: data-type, type of output array
244
- axis: int, axis in result to store samples
245
246
Returns:
247
ndarray: Array of evenly spaced samples
248
"""
249
250
def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):
251
"""
252
Return numbers spaced evenly on a log scale.
253
254
Parameters:
255
- start: array_like, base**start is starting value
256
- stop: array_like, base**stop is final value
257
- num: int, number of samples to generate
258
- endpoint: bool, whether to include stop in samples
259
- base: array_like, base of log space
260
- dtype: data-type, type of output array
261
- axis: int, axis in result to store samples
262
263
Returns:
264
ndarray: Array of samples on log scale
265
"""
266
267
def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0):
268
"""
269
Return numbers spaced evenly on a log scale (geometric progression).
270
271
Parameters:
272
- start: array_like, starting value of sequence
273
- stop: array_like, final value of sequence
274
- num: int, number of samples to generate
275
- endpoint: bool, whether to include stop in samples
276
- dtype: data-type, type of output array
277
- axis: int, axis in result to store samples
278
279
Returns:
280
ndarray: Array of samples on geometric progression
281
"""
282
```
283
284
### Identity and Diagonal Arrays
285
286
Create identity matrices and arrays with values on diagonals.
287
288
```python { .api }
289
def identity(n, dtype=None, like=None):
290
"""
291
Return the identity array.
292
293
Parameters:
294
- n: int, number of rows (and columns) in output
295
- dtype: data-type, data type of output
296
- like: array_like, reference object
297
298
Returns:
299
ndarray: Identity array of shape (n, n)
300
"""
301
302
def eye(N, M=None, k=0, dtype=float, order='C', like=None):
303
"""
304
Return a 2-D array with ones on the diagonal and zeros elsewhere.
305
306
Parameters:
307
- N: int, number of rows in output
308
- M: int, number of columns in output (defaults to N)
309
- k: int, index of diagonal (0 for main diagonal)
310
- dtype: data-type, data type of output
311
- order: {'C', 'F'}, memory layout
312
- like: array_like, reference object
313
314
Returns:
315
ndarray: Array with ones on k-th diagonal
316
"""
317
```
318
319
### Shape Manipulation
320
321
Change the shape and organization of arrays without changing the data.
322
323
```python { .api }
324
def reshape(a, newshape, order='C'):
325
"""
326
Give a new shape to an array without changing its data.
327
328
Parameters:
329
- a: array_like, array to reshape
330
- newshape: int or tuple of ints, new shape
331
- order: {'C', 'F', 'A'}, index order
332
333
Returns:
334
ndarray: Reshaped array
335
"""
336
337
def resize(a, new_shape):
338
"""
339
Return a new array with the specified shape.
340
341
Parameters:
342
- a: array_like, array to resize
343
- new_shape: int or tuple of ints, shape of resized array
344
345
Returns:
346
ndarray: Resized array with new_shape
347
"""
348
349
def ravel(a, order='C'):
350
"""
351
Return a contiguous flattened array.
352
353
Parameters:
354
- a: array_like, input array
355
- order: {'C', 'F', 'A', 'K'}, flattening order
356
357
Returns:
358
ndarray: 1-D array containing elements of input
359
"""
360
361
def flatten(order='C'):
362
"""
363
Return a copy of the array collapsed into one dimension.
364
365
Parameters:
366
- order: {'C', 'F', 'A', 'K'}, flattening order
367
368
Returns:
369
ndarray: 1-D array containing copy of input elements
370
"""
371
```
372
373
### Array Transposition and Axis Manipulation
374
375
Rearrange the axes and dimensions of arrays.
376
377
```python { .api }
378
def transpose(a, axes=None):
379
"""
380
Return an array with axes transposed.
381
382
Parameters:
383
- a: array_like, input array
384
- axes: tuple or list of ints, permutation of axes
385
386
Returns:
387
ndarray: Array with transposed axes
388
"""
389
390
def swapaxes(a, axis1, axis2):
391
"""
392
Interchange two axes of an array.
393
394
Parameters:
395
- a: array_like, input array
396
- axis1: int, first axis
397
- axis2: int, second axis
398
399
Returns:
400
ndarray: Array with swapped axes
401
"""
402
403
def moveaxis(a, source, destination):
404
"""
405
Move axes of an array to new positions.
406
407
Parameters:
408
- a: array_like, array whose axes should be reordered
409
- source: int or sequence of ints, original positions of axes
410
- destination: int or sequence of ints, destination positions
411
412
Returns:
413
ndarray: Array with moved axes
414
"""
415
416
def rollaxis(a, axis, start=0):
417
"""
418
Roll the specified axis backwards.
419
420
Parameters:
421
- a: array_like, input array
422
- axis: int, axis to roll backwards
423
- start: int, position where rolled axis starts
424
425
Returns:
426
ndarray: Array with rolled axis
427
"""
428
429
def roll(a, shift, axis=None):
430
"""
431
Roll array elements along a given axis.
432
433
Parameters:
434
- a: array_like, input array
435
- shift: int or tuple of ints, number of places to shift
436
- axis: int or tuple of ints, axis along which to roll
437
438
Returns:
439
ndarray: Array with elements rolled
440
"""
441
```
442
443
### Dimension Manipulation
444
445
Add or remove array dimensions.
446
447
```python { .api }
448
def squeeze(a, axis=None):
449
"""
450
Remove axes of length one from array.
451
452
Parameters:
453
- a: array_like, input array
454
- axis: None or int or tuple of ints, axes to squeeze
455
456
Returns:
457
ndarray: Input array with length-one axes removed
458
"""
459
460
def expand_dims(a, axis):
461
"""
462
Expand the shape of an array.
463
464
Parameters:
465
- a: array_like, input array
466
- axis: int or tuple of ints, position of new axes
467
468
Returns:
469
ndarray: Array with expanded dimensions
470
"""
471
```
472
473
### Array Joining
474
475
Combine multiple arrays into single arrays.
476
477
```python { .api }
478
def concatenate(arrays, axis=0, out=None, dtype=None, casting="same_kind"):
479
"""
480
Join a sequence of arrays along an existing axis.
481
482
Parameters:
483
- arrays: sequence of array_like, arrays to concatenate
484
- axis: int, axis along which arrays are joined
485
- out: ndarray, destination for result
486
- dtype: data-type, type of output array
487
- casting: {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, casting rule
488
489
Returns:
490
ndarray: Concatenated array
491
"""
492
493
def stack(arrays, axis=0, out=None, dtype=None, casting="same_kind"):
494
"""
495
Join a sequence of arrays along a new axis.
496
497
Parameters:
498
- arrays: sequence of array_like, arrays to stack
499
- axis: int, axis in result array along which input arrays are stacked
500
- out: ndarray, destination for result
501
- dtype: data-type, type of output array
502
- casting: {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, casting rule
503
504
Returns:
505
ndarray: Stacked array with one more dimension than input arrays
506
"""
507
508
def hstack(tup, dtype=None, casting="same_kind"):
509
"""
510
Stack arrays in sequence horizontally (column wise).
511
512
Parameters:
513
- tup: sequence of ndarrays, arrays to stack
514
- dtype: data-type, type of output array
515
- casting: {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, casting rule
516
517
Returns:
518
ndarray: Stacked array
519
"""
520
521
def vstack(tup, dtype=None, casting="same_kind"):
522
"""
523
Stack arrays in sequence vertically (row wise).
524
525
Parameters:
526
- tup: sequence of ndarrays, arrays to stack
527
- dtype: data-type, type of output array
528
- casting: {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, casting rule
529
530
Returns:
531
ndarray: Stacked array
532
"""
533
534
def dstack(tup):
535
"""
536
Stack arrays in sequence depth wise (along third axis).
537
538
Parameters:
539
- tup: sequence of arrays, arrays to stack
540
541
Returns:
542
ndarray: Stacked array along third axis
543
"""
544
545
def block(arrays):
546
"""
547
Assemble an nd-array from nested lists of blocks.
548
549
Parameters:
550
- arrays: nested list of array_like or scalars, block structure
551
552
Returns:
553
ndarray: Block array assembled from input arrays
554
"""
555
```
556
557
### Array Splitting
558
559
Split arrays into multiple sub-arrays.
560
561
```python { .api }
562
def split(ary, indices_or_sections, axis=0):
563
"""
564
Split an array into multiple sub-arrays as views.
565
566
Parameters:
567
- ary: ndarray, array to split
568
- indices_or_sections: int or 1-D array, split points or number of sections
569
- axis: int, axis along which to split
570
571
Returns:
572
list of ndarrays: Sub-arrays as views of ary
573
"""
574
575
def hsplit(ary, indices_or_sections):
576
"""
577
Split an array into multiple sub-arrays horizontally.
578
579
Parameters:
580
- ary: ndarray, array to split
581
- indices_or_sections: int or 1-D array, split points or sections
582
583
Returns:
584
list of ndarrays: Horizontally split sub-arrays
585
"""
586
587
def vsplit(ary, indices_or_sections):
588
"""
589
Split an array into multiple sub-arrays vertically.
590
591
Parameters:
592
- ary: ndarray, array to split
593
- indices_or_sections: int or 1-D array, split points or sections
594
595
Returns:
596
list of ndarrays: Vertically split sub-arrays
597
"""
598
599
def dsplit(ary, indices_or_sections):
600
"""
601
Split array into multiple sub-arrays along 3rd axis (depth).
602
603
Parameters:
604
- ary: ndarray, array to split
605
- indices_or_sections: int or 1-D array, split points or sections
606
607
Returns:
608
list of ndarrays: Sub-arrays split along third axis
609
"""
610
```
611
612
### Array Tiling and Repetition
613
614
Create arrays by tiling or repeating existing arrays.
615
616
```python { .api }
617
def tile(A, reps):
618
"""
619
Construct an array by repeating A the number of times given by reps.
620
621
Parameters:
622
- A: array_like, input array
623
- reps: int or tuple of ints, repetitions along each axis
624
625
Returns:
626
ndarray: Tiled array
627
"""
628
629
def repeat(a, repeats, axis=None):
630
"""
631
Repeat elements of an array.
632
633
Parameters:
634
- a: array_like, input array
635
- repeats: int or array of ints, repetitions for each element
636
- axis: int, axis along which to repeat values
637
638
Returns:
639
ndarray: Array with repeated elements
640
"""
641
```
642
643
### Broadcasting and Indexing Utilities
644
645
Functions for advanced array indexing and broadcasting operations.
646
647
```python { .api }
648
def broadcast(*args):
649
"""
650
Produce an object that mimics broadcasting.
651
652
Parameters:
653
- *args: array_like, arrays to broadcast
654
655
Returns:
656
broadcast object: Iterator that broadcasts input arrays
657
"""
658
659
def broadcast_arrays(*args, subok=False):
660
"""
661
Broadcast any number of arrays against each other.
662
663
Parameters:
664
- *args: array_like, arrays to broadcast
665
- subok: bool, whether to return subclasses
666
667
Returns:
668
list of arrays: Broadcasted arrays
669
"""
670
671
def broadcast_to(array, shape, subok=False):
672
"""
673
Broadcast an array to a new shape.
674
675
Parameters:
676
- array: array_like, array to broadcast
677
- shape: tuple, desired shape
678
- subok: bool, whether to return subclasses
679
680
Returns:
681
ndarray: Broadcast array
682
"""
683
684
def ix_(*args):
685
"""
686
Construct an open mesh from multiple sequences.
687
688
Parameters:
689
- *args: 1-D sequences, coordinate vectors
690
691
Returns:
692
tuple of ndarrays: N-D coordinate arrays for N-D grid
693
"""
694
695
def indices(dimensions, dtype=int, sparse=False):
696
"""
697
Return an array representing the indices of a grid.
698
699
Parameters:
700
- dimensions: sequence of ints, shape of the grid
701
- dtype: dtype, data type of result
702
- sparse: bool, return sparse representation
703
704
Returns:
705
ndarray: Grid indices
706
"""
707
708
def unravel_index(indices, shape, order='C'):
709
"""
710
Convert flat index into tuple of coordinate arrays.
711
712
Parameters:
713
- indices: array_like, array of flat indices
714
- shape: tuple of ints, shape of array into which indices index
715
- order: {'C', 'F'}, index order
716
717
Returns:
718
tuple of ndarrays: Tuple of coordinate arrays
719
"""
720
721
def ravel_multi_index(multi_index, dims, mode='raise', order='C'):
722
"""
723
Convert a tuple of index arrays into flat indices.
724
725
Parameters:
726
- multi_index: tuple of array_like, tuple of index arrays
727
- dims: tuple of ints, shape of array into which indices are applied
728
- mode: {'raise', 'wrap', 'clip'}, specifies how out-of-bounds indices are handled
729
- order: {'C', 'F'}, index order
730
731
Returns:
732
ndarray: Array of flat indices
733
"""
734
735
# Index construction shortcuts
736
mgrid: MGridClass # Dense multi-dimensional meshgrid
737
ogrid: OGridClass # Open (sparse) multi-dimensional meshgrid
738
r_: RClass # Concatenate slices along first axis
739
c_: CClass # Concatenate slices along second axis
740
s_: IndexExpression # Convert slice objects to concatenation along first axis
741
```
742
743
## Usage Examples
744
745
### Creating and Reshaping Arrays
746
747
```python
748
import numpy as np
749
750
# Basic array creation
751
arr = np.array([1, 2, 3, 4, 5])
752
matrix = np.array([[1, 2, 3], [4, 5, 6]])
753
754
# Initialize arrays
755
zeros = np.zeros((3, 4))
756
ones = np.ones((2, 5))
757
identity = np.eye(3)
758
759
# Create ranges
760
range_arr = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
761
linear = np.linspace(0, 1, 5) # [0, 0.25, 0.5, 0.75, 1]
762
763
# Reshape arrays
764
reshaped = matrix.reshape(6, 1) # 6x1 column vector
765
flattened = matrix.ravel() # 1D array [1, 2, 3, 4, 5, 6]
766
```
767
768
### Joining and Splitting Arrays
769
770
```python
771
import numpy as np
772
773
arr1 = np.array([1, 2, 3])
774
arr2 = np.array([4, 5, 6])
775
776
# Join arrays
777
concatenated = np.concatenate([arr1, arr2]) # [1, 2, 3, 4, 5, 6]
778
stacked = np.stack([arr1, arr2]) # [[1, 2, 3], [4, 5, 6]]
779
hstacked = np.hstack([arr1, arr2]) # [1, 2, 3, 4, 5, 6]
780
781
# Split arrays
782
arr = np.array([1, 2, 3, 4, 5, 6])
783
split_arrays = np.split(arr, 3) # [array([1, 2]), array([3, 4]), array([5, 6])]
784
```