numpy
numpy
Arrays in NumPy
localhost:8888/lab/tree/numpy.ipynb 1/7
07/09/2024, 19:30 numpy
newarr = arr.reshape(2, 2, 3)
Original array:
[[1 2 3 4]
[5 2 4 2]
[1 2 0 1]]
---------------
Reshaped array:
[[[1 2 3]
[4 5 2]]
[[4 2 1]
[2 0 1]]]
localhost:8888/lab/tree/numpy.ipynb 2/7
07/09/2024, 19:30 numpy
Original array:
[[1 2 3]
[4 5 6]]
Fattened array:
[1 2 3 4 5 6]
Slicing: Just like lists in Python, NumPy arrays can be sliced. As arrays can be
multidimensional, you need to specify a slice for each dimension of the array. Integer
array indexing: In this method, lists are passed for indexing for each dimension. One-to-
one mapping of corresponding elements is done to construct a new arbitrary array.
Boolean array indexing: This method is used when we want to pick element s from the
array which satisfy some condition.
# 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)
localhost:8888/lab/tree/numpy.ipynb 3/7
07/09/2024, 19:30 numpy
a = np.array([1, 2, 5, 3])
# transpose of array
a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])
localhost:8888/lab/tree/numpy.ipynb 4/7
07/09/2024, 19:30 numpy
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))
Array sum:
[[5 5]
[5 5]]
Array multiplication:
[[4 6]
[6 4]]
Matrix multiplication:
[[ 8 5]
[20 13]]
NymPy’s ufuncs NumPy provides familiar mathematical functions such as sin, cos, exp,
etc.
# exponential values
a = np.array([0, 1, 2, 3])
print ("Exponent of array elements:", np.exp(a))
localhost:8888/lab/tree/numpy.ipynb 5/7
07/09/2024, 19:30 numpy
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'))
localhost:8888/lab/tree/numpy.ipynb 6/7
07/09/2024, 19:30 numpy
What are NumPy Commands? NumPy commands refer to the functions and methods
available in the NumPy library that operate on arrays. Here are a few commonly used
NumPy commands:
localhost:8888/lab/tree/numpy.ipynb 7/7