0
# Array Operations
1
2
Comprehensive array creation, manipulation, and transformation functions that mirror NumPy's API while providing GPU acceleration. These operations form the foundation of CuPy's array programming capabilities.
3
4
## Capabilities
5
6
### Array Creation - Basic
7
8
Create arrays with specific shapes, values, and data types on GPU memory.
9
10
```python { .api }
11
def zeros(shape, dtype=float, order='C'):
12
"""
13
Create array filled with zeros.
14
15
Parameters:
16
- shape: int or sequence of ints, shape of new array
17
- dtype: data type, optional (default: float)
18
- order: {'C', 'F'}, memory layout
19
20
Returns:
21
- ndarray: Array of given shape and type filled with zeros
22
"""
23
24
def ones(shape, dtype=None, order='C'):
25
"""
26
Create array filled with ones.
27
28
Parameters:
29
- shape: int or sequence of ints
30
- dtype: data type, optional
31
- order: {'C', 'F'}, memory layout
32
33
Returns:
34
- ndarray: Array filled with ones
35
"""
36
37
def empty(shape, dtype=float, order='C'):
38
"""
39
Create uninitialized array.
40
41
Parameters:
42
- shape: int or sequence of ints
43
- dtype: data type, optional
44
- order: {'C', 'F'}, memory layout
45
46
Returns:
47
- ndarray: Uninitialized array
48
"""
49
50
def full(shape, fill_value, dtype=None, order='C'):
51
"""
52
Create array filled with fill_value.
53
54
Parameters:
55
- shape: int or sequence of ints
56
- fill_value: scalar, fill value
57
- dtype: data type, optional
58
- order: {'C', 'F'}, memory layout
59
60
Returns:
61
- ndarray: Array filled with fill_value
62
"""
63
64
def eye(N, M=None, k=0, dtype=float, order='C'):
65
"""
66
Create 2D identity matrix.
67
68
Parameters:
69
- N: int, number of rows
70
- M: int, optional, number of columns (default: N)
71
- k: int, optional, diagonal offset (default: 0)
72
- dtype: data type
73
- order: {'C', 'F'}, memory layout
74
75
Returns:
76
- ndarray: 2D array with ones on diagonal
77
"""
78
```
79
80
### Array Creation - From Data
81
82
Convert existing data to CuPy arrays or create arrays with specific patterns.
83
84
```python { .api }
85
def array(obj, dtype=None, copy=True, order='K', subok=False, ndmin=0):
86
"""
87
Create array from array-like object.
88
89
Parameters:
90
- obj: array_like, input data
91
- dtype: data type, optional
92
- copy: bool, whether to copy data
93
- order: {'K', 'A', 'C', 'F'}, memory layout
94
- subok: bool, whether to return subclass
95
- ndmin: int, minimum dimensions
96
97
Returns:
98
- ndarray: Array interpretation of input
99
"""
100
101
def asarray(a, dtype=None, order=None):
102
"""
103
Convert input to array.
104
105
Parameters:
106
- a: array_like, input data
107
- dtype: data type, optional
108
- order: {'C', 'F'}, memory layout
109
110
Returns:
111
- ndarray: Array interpretation of a
112
"""
113
114
def ascontiguousarray(a, dtype=None):
115
"""
116
Return contiguous array in C order.
117
118
Parameters:
119
- a: array_like, input array
120
- dtype: data type, optional
121
122
Returns:
123
- ndarray: Contiguous array
124
"""
125
126
def copy(a, order='K', subok=False):
127
"""
128
Return copy of array.
129
130
Parameters:
131
- a: array_like, input array
132
- order: {'C', 'F', 'A', 'K'}, memory layout
133
- subok: bool, preserve subclass
134
135
Returns:
136
- ndarray: Copy of input array
137
"""
138
```
139
140
### Array Creation - Ranges
141
142
Create arrays with evenly spaced values, coordinate grids, and structured patterns.
143
144
```python { .api }
145
def arange(start, stop=None, step=1, dtype=None):
146
"""
147
Create array with evenly spaced values.
148
149
Parameters:
150
- start: number, start of interval
151
- stop: number, optional, end of interval
152
- step: number, spacing between values
153
- dtype: data type, optional
154
155
Returns:
156
- ndarray: Array of evenly spaced values
157
"""
158
159
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0):
160
"""
161
Create array with evenly spaced values over interval.
162
163
Parameters:
164
- start: scalar, start of sequence
165
- stop: scalar, end of sequence
166
- num: int, number of samples
167
- endpoint: bool, include endpoint
168
- retstep: bool, return step size
169
- dtype: data type, optional
170
- axis: int, axis in result to store samples
171
172
Returns:
173
- ndarray: Array of evenly spaced samples
174
- float: Step size (if retstep=True)
175
"""
176
177
def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):
178
"""
179
Create array with logarithmically spaced values.
180
181
Parameters:
182
- start: scalar, base**start is starting value
183
- stop: scalar, base**stop is final value
184
- num: int, number of samples
185
- endpoint: bool, include endpoint
186
- base: scalar, base of log space
187
- dtype: data type, optional
188
- axis: int, axis in result
189
190
Returns:
191
- ndarray: Logarithmically spaced samples
192
"""
193
194
def meshgrid(*xi, **kwargs):
195
"""
196
Create coordinate matrices from coordinate vectors.
197
198
Parameters:
199
- *xi: array_like, 1D coordinate arrays
200
- copy: bool, return copies
201
- sparse: bool, return sparse grid
202
- indexing: {'xy', 'ij'}, indexing convention
203
204
Returns:
205
- list of ndarray: Coordinate matrices
206
"""
207
```
208
209
### Shape Manipulation
210
211
Change array shapes, dimensions, and memory layout without copying data when possible.
212
213
```python { .api }
214
def reshape(a, newshape, order='C'):
215
"""
216
Give new shape to array without changing data.
217
218
Parameters:
219
- a: array_like, input array
220
- newshape: int or tuple of ints, new shape
221
- order: {'C', 'F', 'A'}, read elements order
222
223
Returns:
224
- ndarray: Reshaped array
225
"""
226
227
def ravel(a, order='C'):
228
"""
229
Return flattened array.
230
231
Parameters:
232
- a: array_like, input array
233
- order: {'C', 'F', 'A', 'K'}, flatten order
234
235
Returns:
236
- ndarray: 1D array
237
"""
238
239
def flatten(a, order='C'):
240
"""
241
Return flattened copy of array.
242
243
Parameters:
244
- a: array_like, input array
245
- order: {'C', 'F', 'A', 'K'}, flatten order
246
247
Returns:
248
- ndarray: 1D copy of input
249
"""
250
```
251
252
### Dimension Changes
253
254
Add, remove, or rearrange array dimensions.
255
256
```python { .api }
257
def expand_dims(a, axis):
258
"""
259
Expand array dimensions.
260
261
Parameters:
262
- a: array_like, input array
263
- axis: int or tuple of ints, position of new axes
264
265
Returns:
266
- ndarray: Array with expanded dimensions
267
"""
268
269
def squeeze(a, axis=None):
270
"""
271
Remove single-dimensional entries.
272
273
Parameters:
274
- a: array_like, input array
275
- axis: None or int or tuple of ints, axes to squeeze
276
277
Returns:
278
- ndarray: Array with squeezed dimensions
279
"""
280
281
def transpose(a, axes=None):
282
"""
283
Permute array dimensions.
284
285
Parameters:
286
- a: array_like, input array
287
- axes: list of ints, permutation of axes
288
289
Returns:
290
- ndarray: Transposed array
291
"""
292
293
def moveaxis(a, source, destination):
294
"""
295
Move axes of array to new positions.
296
297
Parameters:
298
- a: array_like, input array
299
- source: int or sequence of ints, original positions
300
- destination: int or sequence of ints, destination positions
301
302
Returns:
303
- ndarray: Array with moved axes
304
"""
305
306
def swapaxes(a, axis1, axis2):
307
"""
308
Interchange two axes of array.
309
310
Parameters:
311
- a: array_like, input array
312
- axis1: int, first axis
313
- axis2: int, second axis
314
315
Returns:
316
- ndarray: Array with swapped axes
317
"""
318
```
319
320
### Joining Arrays
321
322
Combine multiple arrays along existing or new axes.
323
324
```python { .api }
325
def concatenate(arrays, axis=0, out=None, dtype=None, casting="same_kind"):
326
"""
327
Join arrays along existing axis.
328
329
Parameters:
330
- arrays: sequence of array_like, arrays to join
331
- axis: int, axis along which to join
332
- out: ndarray, optional, destination array
333
- dtype: data type, optional
334
- casting: {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, casting rule
335
336
Returns:
337
- ndarray: Concatenated array
338
"""
339
340
def stack(arrays, axis=0, out=None):
341
"""
342
Join arrays along new axis.
343
344
Parameters:
345
- arrays: sequence of array_like, arrays to stack
346
- axis: int, axis along which to stack
347
- out: ndarray, optional, destination array
348
349
Returns:
350
- ndarray: Stacked array
351
"""
352
353
def vstack(tup):
354
"""
355
Stack arrays vertically (row-wise).
356
357
Parameters:
358
- tup: sequence of ndarrays, arrays to stack
359
360
Returns:
361
- ndarray: Stacked array
362
"""
363
364
def hstack(tup):
365
"""
366
Stack arrays horizontally (column-wise).
367
368
Parameters:
369
- tup: sequence of ndarrays, arrays to stack
370
371
Returns:
372
- ndarray: Stacked array
373
"""
374
375
def dstack(tup):
376
"""
377
Stack arrays depth-wise (along third axis).
378
379
Parameters:
380
- tup: sequence of ndarrays, arrays to stack
381
382
Returns:
383
- ndarray: Stacked array
384
"""
385
```
386
387
### Splitting Arrays
388
389
Divide arrays into multiple sub-arrays.
390
391
```python { .api }
392
def split(ary, indices_or_sections, axis=0):
393
"""
394
Split array into multiple sub-arrays.
395
396
Parameters:
397
- ary: ndarray, input array
398
- indices_or_sections: int or 1D array, split points
399
- axis: int, axis along which to split
400
401
Returns:
402
- list of ndarray: Sub-arrays
403
"""
404
405
def array_split(ary, indices_or_sections, axis=0):
406
"""
407
Split array into multiple sub-arrays (unequal division).
408
409
Parameters:
410
- ary: ndarray, input array
411
- indices_or_sections: int or 1D array, split points
412
- axis: int, axis along which to split
413
414
Returns:
415
- list of ndarray: Sub-arrays
416
"""
417
418
def hsplit(ary, indices_or_sections):
419
"""
420
Split array horizontally.
421
422
Parameters:
423
- ary: ndarray, input array
424
- indices_or_sections: int or 1D array, split points
425
426
Returns:
427
- list of ndarray: Horizontally split arrays
428
"""
429
430
def vsplit(ary, indices_or_sections):
431
"""
432
Split array vertically.
433
434
Parameters:
435
- ary: ndarray, input array
436
- indices_or_sections: int or 1D array, split points
437
438
Returns:
439
- list of ndarray: Vertically split arrays
440
"""
441
```
442
443
### Array Modifications
444
445
Add, remove, or modify array elements and structure.
446
447
```python { .api }
448
def append(arr, values, axis=None):
449
"""
450
Append values to end of array.
451
452
Parameters:
453
- arr: array_like, input array
454
- values: array_like, values to append
455
- axis: int, optional, axis to append along
456
457
Returns:
458
- ndarray: Array with appended values
459
"""
460
461
def resize(a, new_shape):
462
"""
463
Return new array with specified shape.
464
465
Parameters:
466
- a: array_like, input array
467
- new_shape: int or tuple of ints, new shape
468
469
Returns:
470
- ndarray: Resized array
471
"""
472
473
def repeat(a, repeats, axis=None):
474
"""
475
Repeat elements of array.
476
477
Parameters:
478
- a: array_like, input array
479
- repeats: int or array of ints, number of repetitions
480
- axis: int, optional, axis along which to repeat
481
482
Returns:
483
- ndarray: Array with repeated elements
484
"""
485
486
def tile(A, reps):
487
"""
488
Construct array by repeating A.
489
490
Parameters:
491
- A: array_like, input array
492
- reps: int or sequence of ints, repetitions along each axis
493
494
Returns:
495
- ndarray: Tiled array
496
"""
497
```
498
499
### Indexing and Selection
500
501
Advanced indexing, selection, and data extraction operations.
502
503
```python { .api }
504
def take(a, indices, axis=None, out=None, mode='raise'):
505
"""
506
Take elements from array along axis.
507
508
Parameters:
509
- a: array_like, source array
510
- indices: array_like, indices of values to extract
511
- axis: int, optional, axis over which to select
512
- out: ndarray, optional, output array
513
- mode: {'raise', 'wrap', 'clip'}, how to handle out-of-bounds indices
514
515
Returns:
516
- ndarray: Selected elements
517
"""
518
519
def choose(a, choices, out=None, mode='raise'):
520
"""
521
Construct array from index array and choice arrays.
522
523
Parameters:
524
- a: int array, index array
525
- choices: sequence of arrays, choice arrays
526
- out: array, optional, output array
527
- mode: {'raise', 'wrap', 'clip'}, how to handle out-of-bounds indices
528
529
Returns:
530
- ndarray: Selected elements
531
"""
532
533
def compress(condition, a, axis=None, out=None):
534
"""
535
Return selected slices of array along axis.
536
537
Parameters:
538
- condition: 1D array of bools, selection condition
539
- a: array_like, input array
540
- axis: int, optional, axis along which to select
541
- out: ndarray, optional, output array
542
543
Returns:
544
- ndarray: Compressed array
545
"""
546
547
def extract(condition, arr):
548
"""
549
Return elements that satisfy condition.
550
551
Parameters:
552
- condition: array_like, condition array
553
- arr: array_like, input array
554
555
Returns:
556
- ndarray: Selected elements
557
"""
558
```
559
560
## Usage Examples
561
562
### Basic Array Creation
563
564
```python
565
import cupy as cp
566
567
# Create basic arrays
568
zeros_array = cp.zeros((3, 4))
569
ones_array = cp.ones((2, 3), dtype=cp.float32)
570
identity = cp.eye(4)
571
572
# Create from ranges
573
sequence = cp.arange(0, 10, 2) # [0, 2, 4, 6, 8]
574
linear = cp.linspace(0, 1, 5) # [0.0, 0.25, 0.5, 0.75, 1.0]
575
576
# Convert from CPU data
577
import numpy as np
578
cpu_data = np.array([[1, 2], [3, 4]])
579
gpu_data = cp.asarray(cpu_data)
580
```
581
582
### Shape Manipulation
583
584
```python
585
import cupy as cp
586
587
# Create and reshape arrays
588
arr = cp.arange(12)
589
reshaped = arr.reshape(3, 4)
590
flattened = reshaped.ravel()
591
592
# Transpose and move axes
593
transposed = reshaped.T
594
moved = cp.moveaxis(reshaped, 0, 1)
595
596
# Add/remove dimensions
597
expanded = cp.expand_dims(arr, axis=1)
598
squeezed = cp.squeeze(expanded)
599
```
600
601
### Array Joining and Splitting
602
603
```python
604
import cupy as cp
605
606
# Create arrays to join
607
a = cp.array([1, 2, 3])
608
b = cp.array([4, 5, 6])
609
610
# Join arrays
611
concatenated = cp.concatenate([a, b])
612
stacked = cp.stack([a, b], axis=0)
613
vstacked = cp.vstack([a, b])
614
615
# Split arrays
616
arr = cp.arange(9)
617
split_arrays = cp.split(arr, 3) # Split into 3 equal parts
618
```