The array object in NumPy is called ndarray.
We can create a NumPy ndarray object by using the array() function.
print(type(arr))
<class 'numpy.ndarray'>
arr = np.array([1, 2, 3, 4, 5])
arr = np.array((1, 2, 3, 4, 5))
0D array
arr = np.array(42)
1D array
arr = np.array([1, 2, 3, 4, 5])
print(arr[0]) = 1
print(arr[1]) = 2
print(arr[2] + arr[3]) = 7
2D array
arr = np.array([[1, 2, 3], [4, 5, 6]])
print('2nd element on 1st row: ', arr[0, 1]) =2
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('Last element from 2nd dim: ', arr[1, -1]) = 10
3D array
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2]) = 6
NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions
the array have.
print(arr.ndim)
Slicing arrays
We pass slice instead of index like this: [start:end].
We can also define the step, like this: [start:end:step].
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5])
[2 3 4 5]
print(arr[4:])
[5 6 7]
print(arr[:4])
[1 2 3 4]
print(arr[-3:-1])
[5 6]
print(arr[-3:])
[5 6 7]
print(arr[1:5:2]) #step2
[2 4]
print(arr[::2])
[1 3 5 7]
Slicing 2D arrays
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[1, 1:4])
[7 8 9]
print(arr[0:2, 2])
[3 8]
print(arr[0:2, 1:4])
[[2 3 4]
[7 8 9]]
Data types in numpy
i - integer
b - boolean
u - unsigned integer
f - float
c - complex float
m - timedelta
M - datetime
O - object
S - string
U - unicode string
V - fixed chunk of memory for other type ( void )
arr = np.array([1, 2, 3, 4], dtype='S')
print(arr)
print(arr.dtype)
[b'1' b'2' b'3' b'4']
S1
arr = np.array([1, 2, 3, 4], dtype='i4')
print(arr)
print(arr.dtype)
[1 2 3 4]
int32
Converting Data Type on Existing Arrays
The best way to change the data type of an existing array, is to make a copy of the array with the
astype() method.
The astype() function creates a copy of the array, and allows you to specify the data type as a
parameter.
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype('i')
print(newarr)
print(newarr.dtype)
[1 2 3]
int32
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype(int)
print(newarr)
print(newarr.dtype)
[1 2 3]
int64
NumPy Array Copy vs View
The main difference between a copy and a view of an array is that the copy is a new array, and the view
is just a view of the original array.
The copy owns the data and any changes made to the copy will not affect original array, and any
changes made to the original array will not affect the copy.
The view does not own the data and any changes made to the view will affect the original array, and any
changes made to the original array will affect the view.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
arr[0] = 42
print(arr)
print(x)
[42 2 3 4 5]
[1 2 3 4 5]
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
arr[0] = 42
print(arr)
print(x)
[42 2 3 4 5]
[42 2 3 4 5]
Make Changes in the VIEW:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
x[0] = 31
print(arr)
print(x)
[31 2 3 4 5]
[31 2 3 4 5]
Check if Array Owns its Data
As mentioned above, copies owns the data, and views does not own the data, but how can we check
this?
Every NumPy array has the attribute base that returns None if the array owns the data.
Otherwise, the base attribute refers to the original object.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
y = arr.view()
print(x.base)
print(y.base)
None
[1 2 3 4 5]
Shape of an Array
The shape of an array is the number of elements in each dimension.
Get the Shape of an Array
NumPy arrays have an attribute called shape that returns a tuple with each index having the number of
corresponding elements.
import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(arr.shape)
(2, 4)
NumPy Array Reshaping
Reshaping arrays
Reshaping means changing the shape of an array.
The shape of an array is the number of elements in each dimension.
By reshaping we can add or remove dimensions or change number of elements in each dimension.
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(4, 3)
print(newarr)
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Reshape From 1-D to 3-D
newarr = arr.reshape(2, 3, 2)
print(newarr)
[[[ 1 2]
[ 3 4]
[ 5 6]]
[[ 7 8]
[ 9 10]
[11 12]]]
Returns Copy or View?
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
print(arr.reshape(2, 4).base)
[1 2 3 4 5 6 7 8]
The example above returns the original array, so it is a view.
Unknown Dimension
You are allowed to have one "unknown" dimension.
Meaning that you do not have to specify an exact number for one of the dimensions in the reshape
method.
Pass -1 as the value, and NumPy will calculate this number for you.
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
newarr = arr.reshape(2, 2, -1)
print(newarr)
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
Note: We can not pass -1 to more than one dimension.
Flattening the arrays
Flattening array means converting a multidimensional array into a 1D array.
We can use reshape(-1) to do this.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
newarr = arr.reshape(-1)
print(newarr)
[1 2 3 4 5 6]
Note: There are a lot of functions for changing the shapes of arrays in numpy flatten, ravel and also for
rearranging the elements rot90, flip, fliplr, flipud etc. These fall under Intermediate to Advanced section
of numpy.