python NumPy - Data science
Python NumPy
NumPy (short for "Numerical Python") is a fundamental library for scientific computing in Python. It provides support for large, multi-dimensional arrays and matrices, as well as a range of mathematical functions to operate on these arrays.
NumPy's key feature is its powerful "ndarray" object, which is a fast and flexible data structure for storing and manipulating large arrays of numerical data. The arrays can have any number of dimensions and are indexed by a tuple of non-negative integers.
NumPy includes a wide range of mathematical functions, including element-wise operations, mathematical functions (e.g., sin, cos, exp), linear algebra, Fourier transform, and more. These operations can be applied to individual elements of an array or the entire array.
NumPy is an essential library for many other data science libraries, such as Pandas and Scikit-learn. It is also a critical component for scientific computing in Python in general. To use NumPy, you need to import the numpy module by using the following code:
import numpy as np
The np alias is commonly used to refer to the NumPy library in Python code. From there, you can create NumPy arrays and apply NumPy's many functions to them.
How to use NumPy
import numpy as np
# Create a 1D NumPy array
arr = np.array([1, 2, 3, 4, 5])
print("1D Array:", arr)
# Create a 2D NumPy array
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("2D Array:")
print(arr_2d)
# Basic operations on NumPy arrays
arr_sum = arr + arr
arr_product = arr * arr
arr_mean = np.mean(arr)
arr_median = np.median(arr)
print("Array Sum:", arr_sum)
print("Array Product:", arr_product)
print("Array Mean:", arr_mean)
print("Array Median:", arr_median)Output:
1D Array: [1 2 3 4 5]
2D Array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Array Sum: [ 2 4 6 8 10]
Array Product: [ 1 4 9 16 25]
Array Mean: 3.0
Array Median: 3.0This code creates a 1D and 2D array using NumPy's np.array() method, and then performs some basic operations on the arrays using NumPy's mathematical functions.
In this example, we add and multiply the 1D array with itself, and find the mean and median of the array using NumPy's np.mean() and np.median() functions, respectively. We can also see that the 2D array is created and printed using print() function.
Comments
Post a Comment