1. What is Numpy?
Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays.The Numpy is an abbreviation for Numpy Python and is a Python package used in algebric calculations.
import numpy as np
2. Array
2.1 Creating an Array object
Numpy's core data structure is ndarray, which has a similar structure to Python's list. The array may be generated through an np.array() function.
import numpy as np
x = np.array([10, 20, 30])
print(len(x))
2.2 Indexing Array object
Like Python's list, Array can index and assign.
import numpy as np
x = np.array([10, 20, 30])
x0 = x[0]
x2 = x[2]
x[1] = 42
2.3 Slicing Array
We can extract a sequence of elements stored in array using slicing index. By designating start ande end index separated by : operator, we can get a sequence of elements from array.
x = np.array([1, 3, 4, 2, 7, 0, 9])
first_third = x[:3]
middle = x[1:-1]
If additional step is specified when slicing the array, the index skipped by step is sliced.
even = x[0:len(x):2]
odd = x[1:len(x):2]
mul_3 = x[0:len(x):3]
2.4 Result of slicing
The result of array slicing works as a view of an existing array, not a new array. That is, when the sliced array is changed, the value of existing array is also changed. To create a new array, we must copy it using the copy() method.
x = np.array([1, 0, 0, 0, 1])
y = x[1:-1]
z = y.copy()
z[0] = 9
print(x, y, z)
y[1] = 7
print(x, y, z)
2.5 Reverse slicing
Like Python's reverse index, the array starts with -1, -2, ... is available. Likewise, in step slicing, negative number can be used to slice elements of the reduced index.
x = np.array([9, 1, 5, 6, 2, 0, 4, 3, 8, 7])
second_to_last = x[-2]
reversed_x = x[::-1]
first_5_reversed = x[4::-1]
last_5_reversed = x[-1:4:-1]
3. N-dimensional array
The ndarray may be an n-dimensional array and may use a multidimensional array. A previous used array is a 1-dimensional array, and a 2-dimensional array is configured in the form of a list of lists. When indexing 2darray, we can use array2d[row, col]. In the case of 2-dimensional array, the same indexing method as 1-dimensional array is applicable.
array2d[start:end, start:end, step]. We can also store the index values of the desired rows and columns in the list and specify them directly.
2d_array = np.array([[1, 4, 3],
[4, 2, 6],
[3, 7, 9])
2d_array[1, 1] = 42
print(2d_array)
array2d = np.array([
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]
])
x = array2d[:, 3:]
y = array2d[::2,:]
z = array2d[::2,::2]
Source from :
'Data Science > Numpy' 카테고리의 다른 글
[numpy] Processing Datasets, Boolean, and Datatypes in Numpy (0) | 2022.10.03 |
---|---|
[numpy] Arithmetics with Numpy Arrays (0) | 2022.10.03 |