📅  最后修改于: 2023-12-03 15:17:59.008000             🧑  作者: Mango
NumPy (np) is a Python library for performing numerical operations on arrays. It is widely used for scientific computing and is an essential tool for data scientists and machine learning engineers. In this article, we will explore np arrays and their functionalities.
Arrays can be created in many ways. One common way is by using the numpy.array()
function. We can pass a list or tuple of values as an argument, which will be converted to an array.
import numpy as np
arr = np.array([1, 2, 3])
print(arr)
Output:
[1 2 3]
We can also create arrays of zeros or ones using numpy.zeros()
and numpy.ones()
functions. For example,
arr_zeros = np.zeros((2, 3)) # 2 rows, 3 columns
arr_ones = np.ones((4, 4)) # 4 rows, 4 columns
print(arr_zeros)
print(arr_ones)
Output:
[[0. 0. 0.]
[0. 0. 0.]]
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
There are also other ways to create np arrays, such as using numpy.arange()
and numpy.linspace()
.
Similar to Python lists, we can access elements of an np array using square brackets. We can also slice the array to obtain specific elements.
arr = np.array([1, 2, 3, 4, 5])
print(arr[0]) # first element
print(arr[-1]) # last element
print(arr[2:4]) # slice from index 2 to index 4 (exclusive)
Output:
1
5
[3 4]
For a multidimensional array, we can use comma-separated indices to access elements.
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr[0, 0]) # first element
print(arr[1, 2]) # third element in the second row
print(arr[:2, :2]) # slice from the first two rows and columns
Output:
1
6
[[1 2]
[4 5]]
np arrays can perform arithmetic operations such as addition, subtraction, multiplication, and division. The operations are performed element-wise.
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
print(arr1 + arr2)
print(arr1 - arr2)
print(arr1 * arr2)
print(arr1 / arr2)
Output:
[[ 6 8]
[10 12]]
[[-4 -4]
[-4 -4]]
[[ 5 12]
[21 32]]
[[0.2 0.33333333]
[0.42857143 0.5 ]]
np arrays also provide several other functionalities, such as finding the minimum and maximum values in an array, reshaping an array, and transposing an array.
np arrays are a powerful tool for numerical operations and are widely used in data science and machine learning. We covered the basics of creating, indexing, and slicing np arrays and showed how to perform arithmetic operations. I hope this article provides a good introduction to np arrays in Python.