What is NumPy.ndarry?
- Read
- Discuss
NumPy is a powerful library for numerical computing in Python. One of its key features is the ndarray (n-dimensional array) object, a multi-dimensional array used for storing and manipulating large arrays of homogeneous data (i.e., data of the same type, such as integers or floating-point values).
An ndarray can be created by passing a list or tuple of numbers to the numpy.array() function. For example:
import numpy as np
# create a 1-dimensional array
a = np.array([1, 2, 3, 4, 5])
print(a)
The following will be the output:
[1 2 3 4 5]
create a 2-dimensional array
b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(b)
The following will be the output:
[[1 2 3]
[4 5 6]
[7 8 9]]
Numpy arrays are homogeneous, meaning that all elements of the array must be of the same type. Numpy will automatically infer the data type of the array based on the data passed in. You can also specify the data type when creating the array by passing in the dtype parameter.
# create a 2-dimensional array
b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(b.shape)
print(b.ndim)
The following will be the output:
(3, 3)
2
How Do I Create a NumPy Array?
There are several ways to create a NumPy array. Here are a few examples:
Create an array from a Python list or tuple:
import numpy as np
# Create an array from a list
a = np.array([1, 2, 3, 4])
# Create an array from a tuple
b = np.array((5, 6, 7, 8))print(a)print(b)
The following will be the output:
[1 2 3 4]
[5 6 7 8]
Create an array of zeros or ones:
# Create an array of zeros
c = np.zeros((3, 3))
# Create an array of ones
d = np.ones((2, 2))print(c)print(d)
The following will be the output:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
[[1. 1.]
[1. 1.]]
Create an array with a specific data type:
# Create an array with data type float64
e = np.array([1, 2, 3], dtype=np.float64)
# Create an array with data type int32
f = np.array([4, 5, 6], dtype=np.int32)
The following will be the output:
[1. 2. 3.]
[4 5 6]
Create an array with a specific range of values:
# Create an array with values from 0 to 10
g = np.arange(0, 10)
The following will be the output:
[0 1 2 3 4 5 6 7 8 9]
Create an array with evenly spaced values:
# Create an array with evenly spaced values between 0 and 1
h = np.linspace(0, 1, 5)
The following will be the output:
[0. 0.25 0.5 0.75 1. ]
Create a multidimensional array with random values:
# Create a 2x3 array with random values
i = np.random.rand(2,3)
The following will be the output:
[[0.44570137 0.26426047 0.11694156]
[0.0379951 0.22285481 0.86305775]]
These are just a few examples of how to create a NumPy array. There are many other ways to do so, depending on the specific requirements of your project.
How Do I Check The Shape and Size of a NumPy Array?
You can use the shape and size attributes to check the shape and size of a NumPy array, respectively.
Here’s an example:
import numpy as np
# Create a 2x3 array
a = np.array([[1, 2, 3], [4, 5, 6]])
# Check the shape of the array
print(a.shape)
# Check the size of the array
print(a.size)
The following will be the output
(2, 3)
6
The shape attribute returns a tuple representing the dimensions of the array. In the example above, the shape of the array is (2, 3), indicating that it is a 2-dimensional array with 2 rows and 3 columns.
The size attribute returns the total number of elements in the array. In the example above, the array size is 6, because it has 2 rows and 3 columns, and each cell contains one element.
You can also use the ndim attribute to check the number of dimensions in the array:
print(a.ndim) # Output: 2
It will return the number of dimensions in the array (for example, 1 for a 1-dimensional array and 2 for a 2-dimensional array).
How do I Perform Mathematical Operations on a NumPy Array?
You can perform mathematical operations on a NumPy array just like you would with a scalar value. The operations will be applied element-wise to each element in the array.
Here are a few examples of mathematical operations you can perform on a NumPy array:
import numpy as np
# Create an array
a = np.array([1, 2, 3])
# Add a scalar value to the array
b = a + 2
print(b)
# Multiply the array by a scalar value
c = a * 2
print(c)
# Raise the array to a power
d = a ** 2
print(d)
# Perform element-wise division
e = a / 2
print(e)
The following will be the output:
[3 4 5]
[2 4 6]
[1 4 9]
[0.5 1. 1.5]
You can also perform mathematical operations between two arrays of the same shape
a = np.array([1, 2, 3])b = np.array([4, 5, 6])
# Add two arrays element-wisec = a + bprint(c)
# Subtract two arrays element-wised = a - bprint(d)
# Multiply two arrays element-wisee = a * bprint(e)
The following will be the output of the above code.
[5 7 9]
[-3 -3 -3]
[ 4 10 18]
You can also use the NumPy math functions to perform mathematical operations, for example:
import numpy as np
# Create an array
a = np.array([1, 2, 3])
# Perform trigonometric operations
b = np.sin(a)
print(b)
# Perform exponential operations
c = np.exp(a)
print(c)
The following will be the output:
[0.84147098 0.90929743 0.14112001]
[ 2.71828183 7.3890561 20.08553692]
These are just a few examples of the mathematical operations you can perform on a NumPy array. NumPy provides various mathematical functions, including trigonometric, logarithmic, and statistical functions, that you can use to manipulate arrays.
NumPy Matrix Multiplication
Matrix multiplication, also known as the matrix dot product or matrix product, is a binary operation that takes a pair of matrices and produces another matrix. In NumPy, matrix multiplication can be performed using the numpy.dot() function or the * operator.
Here is an example of matrix multiplication using the numpy.dot() function:
import numpy as np
# Create two matrices
matrix_a = np.array([[1, 2], [3, 4]])
matrix_b = np.array([[4, 3], [2, 1]])
# Perform matrix multiplication
result = np.dot(matrix_a, matrix_b)
print(result)
The following will be the output
[[ 8 5] [20 13]]
n the above example, we have created two 2×2 matrices ‘matrix_a’ and ‘matrix_b’ and then performed matrix multiplication using numpy.dot(matrix_a, matrix_b) which gives the resultant matrix.
How Do I Index and Slice a NumPy Array?
You can index and slice a NumPy array using the same syntax as for Python lists.
Here’s an example of how to index a 2-dimensional array:
import numpy as np
# Create a 2-dimensional array
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Get the element at row 0, column 1
print(a[0, 1])
# Get the element at row 1, column 2
print(a[1, 2])
The following will be the output:
2
6
You can also use negative indexing to access elements from the end of the array:
# Get the last element of the last row
print(a[-1, -1])
The following will be the output:
9
Here’s an example of how to slice a 2-dimensional array:
# Get the sub-array of rows 1 and 2, and columns 0 and 1
print(a[1:3, 0:2])
The following will be the output:
[[4 5] [7 8]]
You can also use the : to select all elements along a certain axis:
# Get all rows, column 1
print(a[:,1])
The following will be the output
[2 5 8]
You can also use boolean indexing to select elements in an array based on a condition:
# Get all elements greater than 5
print(a[a > 5])
The following will be the output
[6 7 8 9]
It is important to note that when you slice a numpy array, it returns a view of the original array and not a copy. Any changes you make to the slice will also affect the original array. If you want to create a copy, you can use the copy() method.
b = a[1:3, 0:2].copy()print(b)
The following will be the output
[[4 5] [7 8]]
In summary, indexing and slicing in NumPy allows you to select and manipulate specific elements or sub-arrays of a larger array. Its powerful feature allows you to perform complex operations on large datasets with simple commands.
How Do I Reshape a NumPy Array? NumPy Flatten
You can use the reshape() method to reshape a NumPy array. The method takes two arguments, the number of rows and the number of columns, in that order. For example, to reshape a 1D array with 6 elements into a 2D array with 2 rows and 3 columns, you would use the following code:
import numpy as np
# 1D array with 6 elements
arr = np.array([1, 2, 3, 4, 5, 6])
# reshape the array to 2x3
arr = arr.reshape(2, 3)
The following will be the output:
[1 2 3 4 5 6]
reshaped
[[1 2 3]
[4 5 6]]
NumPy Flatten
You can use the flatten() method to convert a multi-dimensional array to a 1-D array:
# flatten the array to 1-D
arr = arr.flatten()
#or you can use the ravel method
arr = arr.ravel()
How Do I Perform a Dot Product of Two NumPy Arrays?
You can perform a dot product of two NumPy arrays by using the dot() function or the @ operator.
For example:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.dot(a, b)
print(c)
Or using @ sign
d = a @ b
print(d)
The following will be the output
32
How Do I Perform a Transpose of a NumPy Array?
You can perform the transpose of a NumPy array by using the T attribute or the transpose() function.
Using T attribute
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
b = a.T
print(b)
Using transpose()
c = np.transpose(a)
print(c)
The following will be the output:
[[1 2 3]
[4 5 6]]
Transpose
[[1 4]
[2 5]
[3 6]]
Both will give the same result which is a transposed version of the array, with the rows and columns flipped.
Another way to perform transpose is:
d = a.transpose()
How do I perform element-wise operations on a NumPy array?
You can perform element-wise operations on a NumPy array by using basic arithmetic operators such as +, -, *, / and **. These operators act element-wise on the array, rather than on the entire array as a whole.
For example:
Addition
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = a + b
print(c)
The following will be the output:
[5 7 9]
Multiplication
d = a * b
print(d)
The following will be the output:
[ 4 10 18]
You can also use numpy functions like numpy.add(), numpy.subtract(), numpy.multiply(), numpy.divide(), numpy.power() and numpy.mod() to perform element-wise operations.
numpy.add()
g = np.add(a,b)
print(g)
The following will be the output:
[5 7 9]
numpy.subtract()
h = np.subtract(a,b)
print(h)
The following will be the output:
[-3 -3 -3]
numpy.multiply()
i = np.multiply(a,b)
print(i)
The following will be the output:
[ 4 10 18]
numpy.divide()
j = np.divide(a,b)
print(j)
The following will be the output:
[ 0.25 0.4 0.5 ]
numpy.power()
k = np.power(a,b)
print(k)
The following will be the output:
[ 1 32 729]
Note that, the output of element-wise operation depends on the shape and size of the arrays.
How Do I Merge Multiple NumPy Arrays into a Single Array?
You can merge multiple NumPy arrays into a single array using the numpy.concatenate() function. The numpy.concatenate() function takes a tuple or a list of arrays as its first argument and an axis along which the arrays will be concatenated as its second argument. By default, the axis is 0, which means that the arrays will be concatenated along the rows.
For example:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.concatenate((a, b))
print(c)
The following will be the output:
[1 2 3 4 5 6]
For 2-D arrays, you can use concatenate along the rows by default or along the columns by specifying the axis as 1:
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
c = np.concatenate((a, b))
print(c)
The following will be the output:
[[1 2][3 4][5 6][7 8]]
How to Convert NumPy Array to List?
Converting a numpy array to a list in Python is a straightforward process. The most common method to convert a numpy array to a list is the tolist() method.
For example, let’s say we have a numpy array of fruits:
import numpy as np
fruits = np.array(["apple", "banana", "orange"])
To convert this array to a list, we simply call the tolist() method on the array:
fruits_list = fruits.tolist()
print(fruits_list)
The following will be the output:
["apple", "banana", "orange"]
Another way to convert a numpy array to a list is by using the list() function. This method works for any iterable, including numpy arrays:
fruits_list = list(fruits)
print(fruits_list)
Both of the above methods will produce the same output: a list of fruits [“apple”, “banana”, “orange”].
It is important to note that the tolist() method and list() function create a new list, and don’t modify the original numpy array. This means that any changes made to the new list will not affect the original array.
How to Convert DataFrame to NumPy Array?
Converting a DataFrame to a NumPy array is a simple process in Pandas. The easiest way to do this is to use the values attribute of the DataFrame, which returns the underlying NumPy array. Here is an example of how to convert a DataFrame to a NumPy array:
import pandas as pd
import numpy as np
# Create a sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
# Convert DataFrame to NumPy array
np_array = df.values
print(np_array)
The following will be the output
array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
Alternatively, you can use the to_numpy() method of the DataFrame. The to_numpy() method returns an array with the same data as the DataFrame, but with the dtype determined by the dtype of the DataFrame’s columns.
np_array = df.to_numpy()
It’s worth noting that if your dataframe has any non-numeric columns, these will be dropped when converting to a NumPy array.
Leave a Reply
You must be logged in to post a comment.