Unit 4 Python Numpy
Unit 4 Python Numpy
Python Numpy
Note: Type of array can be explicitly defined while creating the array.
Example 1:
Example 2:
1
# Python program to demonstrate indexing in numpy array
import numpy as np
# Initial Array
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])
print("Initial Array: ")
print(arr)
# Defining Array 1
a = np.array([[1, 2],
[3, 4]])
# Defining Array 2
b = np.array([[4, 3],
[2, 1]])
Example:
2
import numpy as np
Example:
import numpy as np
Example:
Flatten array: We can use flatten method to get a copy of the array collapsed into one
dimension.
arr = np.array([[1, 2, 3], [4, 5, 6]])
3
flat_arr = arr.flatten()
# An exemplar array
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])
# Slicing array
temp = arr[:2, ::2]
print ("Array with first 2 rows and alternate"
"columns(0 and 2):\n", temp)
4
Operations on a single NumPy array
We can use overloaded arithmetic operators to do element-wise operations on the array to
create a new array. In the case of +=, -=, *= operators, the existing array is modified.
a = np.array([1, 2, 5, 3])
# transpose of array
a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])
Many unary operations are provided as a method of ndarray class. This includes sum, min,
max, etc. These functions can also be applied row-wise or column-wise by setting an axis
parameter.
5
[4, 7, 2],
[3, 1, 9]])
a = np.array([[1, 2],
[3, 4]])
b = np.array([[4, 3],
[2, 1]])
# add arrays
print ("Array sum:\n", a + b)
# matrix multiplication
print ("Matrix multiplication:\n", a.dot(b))
6
# Python program to demonstrate sorting in numpy
import numpy as np
a = np.array([[1, 4, 2],
[3, 4, 6],
[0, -1, 5]])
# sorted array
print ("Array elements in sorted order:\n",
np.sort(a, axis = None))
# Creating array
arr = np.array(values, dtype = dtypes)
print ("\nArray sorted by names:\n",
np.sort(arr, order = 'name'))
Example:
# dtype parameter
import numpy as np
a = np.array([1, 2, 3], dtype = complex)
print a
7
a = np.array([[1,2,3],[4,5,6]])
a.shape = (3,2)
print a
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = a.reshape(3,2)
print b
# now reshape it
b = a.reshape(2,4,3)
print b
x = [1,2,3]
a = np.asarray(x)
print a
# dtype is set
import numpy as np
x = [1,2,3]
a = np.asarray(x, dtype = float)
print a
x = (1,2,3)
a = np.asarray(x)
print a
8
# ndarray from list of tuples
import numpy as np
x = [(1,2,3),(4,5)]
a = np.asarray(x)
print a
numpy.arange
This function returns an ndarray object containing evenly spaced values within a given
range. The format of the function is as follows −
numpy.arange(start, stop, step, dtype)
1 start
The start of an interval. If omitted, defaults to 0
2 stop
The end of an interval (not including this number)
3 step
Spacing between values, default is 1
dtype
4 Data type of resulting ndarray. If not given, data type of input is
used
# start and stop parameters set
import numpy as np
x = np.arange(10,20,2)
print x
import numpy as np
a = np.arange(10)
s = slice(2,7,2)
print a[s]
import numpy as np
a = np.arange(10)
9
b = a[2:7:2]
print b
import numpy as np
a = np.array([[1,2,3],[3,4,5],[4,5,6]])
print a
import numpy as np
x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]])
# slicing
z = x[1:4,1:3]
NumPy – Broadcasting
10
The term broadcasting refers to the ability of NumPy to treat arrays of different shapes
during arithmetic operations. Arithmetic operations on arrays are usually done on
corresponding elements.
import numpy as np
a = np.array([1,2,3,4])
b = np.array([10,20,30,40])
c=a*b
print c
import numpy as np
a = np.array([[0.0,0.0,0.0],[10.0,10.0,10.0],[20.0,20.0,20.0],[30.0,30.0,30.0]])
b = np.array([1.0,2.0,3.0])
Example
import numpy as np
print(sum)
11
Compatibility Rules for Broadcasting
Broadcasting only works with compatible arrays. NumPy compares a set of array
dimensions from right to left.
array1 = shape(6, 7)
array2 = shape(6, 1)
Here, array1 and array2 are arrays with different
dimensions (6,7) and (6,1) respectively.
The dimension length 7 and 1 are compatible because one of them is 1.
Similarly, 6 and 6 are compatible since they are the same.
As both sets of dimensions are compatible, the arrays are broadcastable.
Broadcastable Shapes
(6, 7) and (6, 7)
Two arrays need not have the same number of dimensions to be broadcastable.
The last set of shapes is broadcastable because the right-most dimensions are
both 7.
Non-Broadcastable Shapes
(6, 7) and (7, 6)
12
(6, 7) and (6, )
The last set of shapes is not broadcastable because the right-most dimensions are
not the same.
Comparision:
import numpy as np
x = np.array([1, 2, 3, 4, 5])
print(x<3)
print(x<=3)
print(x!=3)
print(x==3)
print(2*x)
print(x**2)
print((2 * x) == (x ** 2))
Example:
rng = np.random.RandomState(0)
x = rng.randint(10, size=(3, 4))
print(x)
print(x<6)
np.less(x, 6)
Example:
import numpy as np
13
x = np.array([[1, 4, 2],
[3, 4, 6],
[0, -1, 5]])
#x = np.array([1, 2, 3, 4, 5])
print(np.count_nonzero(x > 6))
print(np.sum(x < 6))
# how many values less than 6 in each row?
print(np.sum(x < 6, axis=1)) #row wise count
# are there any values greater than 8?
print(np.any(x > 4))
# are all values less than 10?
print(np.all(x < 10))
# are all values equal to 6?
print(np.all(x == 6))
# are all values in each row less than 8?
print(np.all(x < 8, axis=1))
print(x[x < 5])
Now to select these values from the array, we can simply index on this Boolean array;
this is known as a masking operation:
Boolean Logic
A = np.array([1, 0, 1, 0, 1, 0], dtype=bool)
B = np.array([1, 1, 1, 0, 1, 1], dtype=bool)
print(A | B)
x = np.arange(10)
print((x > 4) & (x < 8))
import numpy as np
14
print(select_elements)
Example
import numpy as np
print("Simple Indexing:",simple_indexing) # 4
print("Fancy Indexing:",fancy_indexing) # [2 3 6 8]
print(sorted_array)
Example
#We could also use fancy indexing to sort the array in descending order.
import numpy as np
array1 = np.array([3, 2, 6, 1, 8, 5, 7, 4])
We can also assign new values to specific elements of a NumPy array using fancy
indexing. For example,
import numpy as np
print(array1)
import numpy as np
# create a 2D array
array1 = np.array([[1, 3, 5],
[11, 7, 9],
[13, 18, 29]])
print(selected_rows)
Structured arrays
16
Structured arrays are ndarrays whose datatype is a composition of simpler datatypes
organized as a sequence of named fields. For example,
Here x is a one-dimensional array of length two whose datatype is a structure with three
fields: 1. A string of length 10 or less named ‘name’, 2. a 32-bit integer named ‘age’, and 3. a
32-bit float named ‘weight’.
import numpy as np
a = np.array([('Sana', 2, 21.0), ('Mansi', 7, 29.0)],
dtype=[('name', (np.str_, 10)), ('age', np.int32), ('weight', np.float64)])
max_age = np.max(a['age'])
min_age = np.min(a['age'])
17
Concatenating Structured Array
import numpy as np
a = np.array([('Sana', 2, 21.0), ('Mansi', 7, 29.0)],
dtype=[('name', (np.str_, 10)), ('age', np.int32), ('weight', np.float64)])
import numpy as np
a = np.array([('Sana', 2, 21.0), ('Mansi', 7, 29.0)],
dtype=[('name', (np.str_, 10)), ('age', np.int32), ('weight', np.float64)])
reshaped_a = np.reshape(a, (2, 1))
print(reshaped_a)
18