Skip to main content

np.array()

Creates a NumPy array from a list or tuple.
arr = np.array([1,2,4])
print(arr)
Output:
[1 2 4] 

.ndim

Returns the number of dimensions of the array.
arr.ndim
Output:
1

np.array(34)

Creates a scalar (0D) NumPy array.
arr2 = np.array(34)
arr2.ndim
Output:
0

.shape

Returns the shape as (rows, columns).
arr3 = np.array([[1,3,4],[2,34,5]])
arr3.shape
Output:
(2, 3)

np.arange()

Creates numbers within a range using step size.
np.arange(1,10,2)
Output:
[1 3 5 7 9]

np.linspace()

Creates evenly spaced numbers between two values.
np.linspace(0,1,5)
Output:
[0.   0.25 0.5  0.75 1.  ]

np.logspace()

Creates numbers in logarithmic scale.
np.logspace(1,3,3)
Output:
[  10.  100. 1000.]

np.zeros()

Creates an array filled with zeros.
np.zeros(4)
Output:
[0. 0. 0. 0.]

2D Example

np.zeros([3,2])
Output:
[[0. 0.]
 [0. 0.]
 [0. 0.]]

np.ones()

Creates an array filled with ones.
np.ones([3,2])
Output:
[[1. 1.]
 [1. 1.]
 [1. 1.]]

np.full()

Creates an array filled with a custom value.
np.full(10,2)
Output:
[2 2 2 2 2 2 2 2 2 2]

2D Example

np.full([2,4],5)
Output:
[[5 5 5 5]
 [5 5 5 5]]

np.empty()

Creates an uninitialized array with random garbage values.
np.empty([2,3])
Output:
[[6.92029351e-310 6.92029351e-310 0.00000000e+000]
 [0.00000000e+000 0.00000000e+000 0.00000000e+000]]
(Output varies every time)

np.random.rand()

Generates random numbers between 0 and 1.
np.random.rand(5)
Output:
[0.12 0.45 0.89 0.34 0.67]
(Random output)

np.random.randn()

Generates random numbers from normal distribution.
np.random.randn(2,3)
Output:
[[ 0.52 -1.12  0.44]
 [ 1.32  0.87 -0.29]]
(Random output)

np.random.randint()

Generates random integers within a range.
np.random.randint(10,100,size=5)
Output:
[23 45 89 12 67]
(Random output)

.dtype

Returns datatype of array elements.
arr = np.array([1,2,3])
arr.dtype
Output:
dtype('int64')

astype()

Converts array datatype into another datatype.
arr.astype(np.float64)
Output:
array([1., 2., 3.])

.size

Returns total number of elements.
arr.size
Output:
6

.itemsize

Returns memory size of one element in bytes.
arr.itemsize
Output:
8

reshape()

Changes array shape without changing data.
arr = np.array([1,2,3,4,5,6])
arr.reshape(2,3)
Output:
[[1 2 3]
 [4 5 6]]

ravel()

Converts multi-dimensional array into 1D view.
arr.reshape(2,3).ravel()
Output:
[1 2 3 4 5 6]

flatten()

Converts array into independent 1D copy.
arr.reshape(2,3).flatten()
Output:
[1 2 3 4 5 6]

Arithmetic Operations on NumPy Arrays

NumPy supports direct arithmetic operations on arrays.
arr1 = np.array([1,2,3])
arr2 = np.array([4,5,6])

print(arr1 + arr2)
print(arr1 - arr2)
print(arr1 * arr2)
print(arr1 / arr2)
Output:
[5 7 9]
[-3 -3 -3]
[ 4 10 18]
[0.25 0.4  0.5 ]

Universal Functions (ufuncs)

Universal functions perform element-wise operations efficiently.

np.sin()

Calculates sine value for each element.
angles = np.array([0,np.pi,np.pi/2])

print(np.sin(angles))
Output:
[0.0000000e+00 1.2246468e-16 1.0000000e+00]

Indexing and Slicing

Access Elements

arr = np.array([10,20,30,40,50])

print(arr[-1])
Output:
50

Slicing

arr[::2]
Output:
[10 30 50]

Reverse Slicing

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

a[-1:-3:-1]
Output:
[5 4]

Multidimensional Slicing

matrix = np.array([[1,2,3],
                   [4,5,6],
                   [7,8,9]])

print(matrix[0:2])
Output:
[[1 2 3]
 [4 5 6]]

Specific Rows and Columns

print(matrix[1:,1:])
Output:
[[5 6]
 [8 9]]

Index Array using np.take()

Selects elements using index positions.
arr = np.array([10,20,30,40,50])

ind = [0,2]

print(np.take(arr,ind))
Output:
[10 30]

Iterating NumPy Arrays

np.nditer()

Iterates element by element.
arr=np.array([[1,2],[3,4]])

for x in np.nditer(arr):
  print(x, end=" ")
Output:
1 2 3 4

np.ndenumerate()

Returns index and value while iterating.
for ind, x in np.ndenumerate(arr):
  print(ind,x)
Output:
(0, 0) 1
(0, 1) 2
(1, 0) 3
(1, 1) 4

Views vs Copies

View

Changes affect original array.
arr = np.array([1,2,4,5,6])

view = arr[1:4]

view[1] = 3

print(arr)
Output:
[1 2 3 5 6]

Copy

Changes do not affect original array.
arr1 = np.array([1,2,4,5,6])

copy = arr1[1:4].copy()

copy[0] = 100

print(arr1)
print(copy)
Output:
[1 2 4 5 6]
[100   4   5]

Transpose of Matrix

transpose()

Converts rows into columns.
mat = np.array([[1,2],[3,4]])

print(mat.transpose())
Output:
[[1 3]
 [2 4]]

swapaxes()

Swaps two specific axes in multidimensional arrays.
mat = np.array([[[1,2],[3,4]]])

swap = np.swapaxes(mat,0,1)

print(swap.shape)
Output:
(2, 1, 2)

Concatenation and Stacking

np.concatenate()

Joins arrays into one array.
arr1 = np.array([1,2,3])
arr2 = np.array([4,5,6])

combine = np.concatenate((arr1,arr2))

print(combine)
Output:
[1 2 3 4 5 6]

np.vstack()

Stacks arrays vertically.
vstack = np.vstack((arr1,arr2))

print(vstack)
Output:
[[1 2 3]
 [4 5 6]]

np.hstack()

Stacks arrays horizontally.
hstack = np.hstack((arr1,arr2))

print(hstack)
Output:
[1 2 3 4 5 6]

np.stack()

Stacks arrays along a new axis.
stack = np.stack((arr1,arr2),axis=0)

print(stack)
Output:
[[1 2 3]
 [4 5 6]]

Splitting Arrays

np.split()

Splits array into equal parts.
arr = np.array([1,2,3,4])

print(np.split(arr,2))
Output:
[array([1, 2]), array([3, 4])]

Repeat vs Tile

np.repeat()

Repeats each element multiple times.
arr = np.array([1,2,3])

print(np.repeat(arr,3))
Output:
[1 1 1 2 2 2 3 3 3]

np.tile()

Repeats whole array multiple times.
print(np.tile(arr,3))
Output:
[1 2 3 1 2 3 1 2 3]

Aggregate Functions

np.sum()

Returns sum of elements.
print(np.sum(arr))
Output:
6

np.std()

Returns standard deviation.
np.std(arr)
Output:
0.816496580927726

np.min()

Returns minimum value.
np.min(arr)
Output:
1

Sum by Axis

matrix = np.array([[1,2,3],
                   [4,5,6],
                   [7,8,9]])

print(np.sum(matrix,axis=0))
print(np.sum(matrix,axis=1))
Output:
[12 15 18]
[ 6 15 24]

np.cumsum()

Returns cumulative sum.
print(np.cumsum(arr))
Output:
[1 3 6]

np.cumprod()

Returns cumulative product.
print(np.cumprod(arr))
Output:
[1 2 6]

Conditional Operations

np.where()

Applies condition and returns values.
res = np.where(arr<2,"low","high")

print(res)
Output:
['low' 'high' 'high']

np.argwhere()

Returns indexes where condition is true.
print(np.argwhere(arr>0))
Output:
[[0]
 [1]
 [2]]

Masking in Arrays

np.logical_and()

Checks multiple conditions together.
array = np.array([100,2,3,4,5,6])

mask = np.logical_and(array>3,array<6)

print(mask)
Output:
[False False False  True  True False]

np.logical_or()

Returns true if any condition is true.
mask = np.logical_or(array>3,array<6)

print(mask)
Output:
[ True  True  True  True  True  True]

Broadcasting

Broadcasting automatically applies operations across arrays.
image = np.array([[200,150],[100,250]])

brightness = image + 50

print(brightness)
Output:
[[250 200]
 [150 300]]

Vectorization

Applies functions efficiently without loops.
def square(x):
  return x*x

vfunc = np.vectorize(square)

arr = np.array([1,2,3])

print(vfunc(arr))
Output:
[1 4 9]

Missing Values

np.nan

Represents missing values.
a = np.array([1,2,3,np.nan,5])

print(a)
Output:
[ 1.  2.  3. nan  5.]

np.isnan()

Checks for NaN values.
print(np.isnan(a))
Output:
[False False False  True False]

Infinite Values

np.isinf()

Checks infinite values.
b = np.array([1,np.nan,np.inf,10.2,40])

print(np.isinf(b))
Output:
[False False  True False False]

np.nan_to_num()

Converts NaN and Inf into numbers.
new_b = np.nan_to_num(b)

print(new_b)
Output:
[1.00000000e+000 0.00000000e+000 1.79769313e+308 1.02000000e+001
 4.00000000e+001]