NumPy (Numerical Python) là một thư viện của Python phù
hợp để xử lý số và dữ liệu khoa học. Nó có các đối tượng mảng
N-chiều và nhiều phương pháp để xứ lý chúng.
Tạo vector bằng NumPy
# Load library
import numpy as np
# Create a vector as a row
vector_row = np.array([1, 2, 3])
# Create a vector as a column
vector_column = np.array([[1],[2],[3]])
Một vector chính là một array 1 chiều duy nhất. Do đó để
tạo vector đơn giản chúng ta tạo 1 array 1 chiều.
Tạo matrix bằng NumPy
# Load library
import numpy as np
# Create a matrix
matrix = np.array([[1, 2],
[1, 2],
[1, 2]])
Chúng ta có thể tạo matrix bằng cách tạo Numpy array hai
chiều. Tuy nhiên ít ai sử dụng matrix bởi vì cấu trúc dữ liệu
chuẩn của NumPy chính là mảng và hầu hết các thao tác trong
Numpy đều trả về mảng chứ không phải matrix.
Tạo ma trận thư thớt (Sparse Matrix)
# Load libraries
import numpy as np
from scipy import sparse
# Create a matrix
matrix = np.array([[0, 0],
[0, 1],
[3, 0]])
# Create compressed sparse row (CSR) matrix
matrix_sparse = sparse.csr_matrix(matrix)
Có rất nhiều tình huống trong máy học mà ở đó có một
lượng lớn dữ liệu đều là 0. Ví dụ tưởng tượng chúng ta có
dataset về các phim trên netflix là các cột và hàng là số người
xem xem đó. Rõ ràng là chúng ta có thể có hàng ngàn cột và
thậm chí hàng triệu dịng tuy nhiên hầu hết các dịng sẽ có giá
trị 0 bởi vì khơng phải ai cũng xem phim nào đó.
Ma trận thưa thớt là ma trận mà hầu hết các thành phần
của nó = 0. Ma trận thưa thớt chỉ lưu các giá trị khác không và
cho các giá trị cịn lại = 0, nhờ đó tiết kiệm được q trình tính
tốn. Trong ví dụ trên chúng ta thấy được ma trận thưa thớt của
ma trận ở trên
# View sparse matrix
print(matrix_sparse)
(1, 1)
1
(2, 0)
3
Cột đầu tiên của ma trận thưa thớt chính là chỉ mục của
các giá trị khác 0. Chỉ mục 1 chính là chỉ có một giá trị khác 0 ở
dịng thứ hai (dịng thứ 1 có chỉ mục 0) cột thứ 2 (cột thứ 1 có
chỉ mục là 0) và giá trị đó là 1. Tương tự ta có giá trị 3 ở dòng 2
và cột 1. Ma trận thưa thớt như vậy gọi là ma trận thưa thớt nén
(compressed sparse row (CSR) matrices).
# Create larger matrix
matrix_large = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[3, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
# Create compressed sparse row (CSR) matrix
matrix_large_sparse = sparse.csr_matrix(matrix_large)
# View original sparse matrix
print(matrix_sparse)
(1, 1)
1
(2, 0)
3
# View larger sparse matrix
print(matrix_large_sparse)
(1, 1)
1
(2, 0)
3
Chúng ta có thể nhận thấy được lợi thế của ma trận thưa
thớt khi ma trận của chúng ta lớn hơn. Dù lớn đến cỡ nào thì ma
trận thưa thớt của cả hai dataset đều giống nhau, và tiết kiệm
tính tốn đến tối giản.
Có rất nhiều loại ma trận thưa thớt như compressed sparse
column, list of lists, và dictionary of keys. Mỗi loại ma trận có
cách sử dụng khác nhau do đó cần xem xét cẩn thận trước khi
chọn loại ma trận.
Đối tượng mảng NumPy
Trong Numpy thì các đối tượng mảng đa chiều là đối tượng
cơ bản nhất. Mảng Numpy chỉ chứa cùng loại giá trị, khơng
giống như Python list. Trong Numpy thì chiều của mảng được đề
cập đến là trục. Ví dụ mảng 1 chiều ([1,2,3]) thì được xem như
là có 1 trục với 3 thành phần hay nói cách khác nó có trục có độ
dài là 3. Mảng hai chiều sẽ có hai trục: trục thứ nhất (axis = 0)
có chiều dài là 2 và trục thứ hai (axis=1) có chiều dài là 3.
Creating
the
NumPy
array
In NumPy, we can create the N-D array using the array()
function;
We
can
create a NumPy array by passing any regular Python list or
tuple
in
the
array
function. The following is an example of the same:
()
In this example, we have used a regular Python list to create
the
one
dimensional array (array1_1D), and second, we have used a
standard
Python
tuple and made a 1-D NumPy array (array2_1D)
We can also explicitly pass the datatypes of the array using the
dtype
option
of
the array () function. Let’s see the following example:
So, if we want to datatype int or float, and so on, that can be
passed
instead
of complex datatype. Later in the chapter, we will see the
various
types
types
of
in
data
NumPy.
From this example, we can make another observation that the
array()
function
transforms the sequences ( [1,2,3,4,5] and (2,3,4,5)) into 1-D
Array.
So,
if
we
need to create a 2-D Array, then we have to pass sequences of
sequences,
and
if we need a 3-D Array, then sequences of sequences, and so
on.
Let’s
see
the
following example of 2-D array creation using the array()
function:
We passed the two tuples list in this coding snippet, and the
array
function
transformed it into a 2-D array. Here, the length of the first axis
is
two
and
the
second,
three.
In NumPy, we can create special arrays, such as an array of
zeros,
empty
ones,
array,
and
and
an
so
on.
The following are the examples for some special arrays:
Tạo mảng Numpy với giá trị cho trước
Numpy có 1 số hàm cho phép tạo ra các mảng với các giá
trị cho trước.
# Load library
import numpy as np
# Generate a vector of shape (1,5) containing all zeros
vector = np.zeros(shape=5)
# View the vector
print(vector)
array([0., 0., 0., 0., 0.])
Với hàm zero() chúng ta có thể tạo mảng Numpy tất cả
bằng 0. Đối số shape quy định số lượng thành phần trong mảng
là 5. Kết quả là ta có mảng 5 giá trị 0.
Hàm zero cũng cho phép tạo matrix gồm các giá trị 0. Đối
số shape(2,3) nghĩa là tạo axis =0 là có 2 hàng và axis =1 là có
3 cột.
Chúng ta cũng có thể tạo ra mảng với giá trị 1 bằng hàm
ones
Hàm ones với đối số (2,3) tạo ra ma trận hai hàng và 3 cột
các giá trị 1.
Ngồi ra chúng ta cịn có thể dùng hàm fulle để tạo ra ma
trận bất kỳ giá trị cho trước nào
# Generate a matrix of shape (3,3) containing all two
matrix = np.full((3,3),2)
# View the vector
print(matrix)
# Generate a matrix of shape (3,3) containing all 1 and 2
matrix = np.full((2, 2), [1, 2])
# View the vector
print(matrix)
Chúng ta cịn có hàm empty giúp tạo ra các mảng hoặc ma
trận có giá trị ngẫu nhiên vừa chứa 0 vừa chứa khác không.
matrix = np.empty((3, 3))
# View the vector
print(matrix)
Việc tạo ra các mảng hay matrix với các giá trị cho trước
phục vụ cho nhiều mục đích chẳng hạn như giúp code thêm
hiệu quả hoặc tạo ra dữ liệu ảo để kiểm tra thuật toán.
Tạo mảng Numpy bằng list và tuple
Chúng ta có thể tạo ra mảng Numpy bằng cách sử dụng
list trong Python với hàm asarray().
Trong ví dụ trên chúng ta đã truyền list t1 vào hàm
asarray() với định dạng dtype=’int16’ và nó trả về tương
đương mảng 1 chiều và matrix hai chiều.
Chúng ta cũng có thể tạo mảng Numpy bằng cách sử dụng
tuple của Python cũng với hàm asarray().
Tạo mảng Numpy bằng dãy số
Chúng ta có thể tạo ra một mảng Numpy bằng dãy số với
hàm arrange(star,stop,step).
Indexing and slicing trong mảng NumPy
Giống như list trong Python chúng ta cũng có thể indexing
và slicing. Numpy array cũng có index 0 nghĩa là thành phần
đầu tiên của mảng chính là chỉ mục 0. Nó cũng hỗ trợ chỉ mục
âm nghĩa là -1, tượng trưng cho thành phần cuối cùng.
Indexing và slicing cho mảng 1 chiều
# Load library
import numpy as np
# Create row vector
vector = np.array([1, 2, 3, 4, 5, 6])
# Create matrix
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Chọn 1 thành phần trong vector
vector[2]
# Chọn thành phần cuối cùng
vector[-1]
# Chọn tất cả các thành phần của vector
vector[:]
# Chọn 1 khoảng thành phần của vector
vector[:3]
# Chọn 1 khoảng thành phần của vector
vector[3:]
# Đảo ngược vector
vector[::-1]
Indexing và slicing cho 1 matrix
Để slicing cho 1 matrix chúng ta cần phải xác định slices
cho cả hàng và cột. Cú pháp như sau:
[dim1_slice,cdim2_slice]
Hoặc
[row_slice,column_slice]
Hoặc
[dim_1_slice : dim_1_slice: dim1_slice… dim_n_slie] trong
đó giá trị index ban đầu được thêm vào cịn giá trị cuối thì bị
loại ra.
# Chọn 1 hàng nhất định của ma trận
b[0]
# Chọn 1 số hàng liên tục của ma trận
b[0:2]
# Chọn một số hàng và một số cột trong matrix
matrix[:2,:]
b[0:2,0:2]
b[2:,4:]
Data
types
in
NumPy
NumPy supports a bigger number of numeric types than Python
does.
Table
10.1 is the list of basic data types in NumPy
In NumPy array, all the elements have the same data type,
which
means,
if
there is any n-D array, ‘a’ is a type of int8 (8-bit integer), then
each
element
of
this array will be able to store an 8-bit integer value.
Getting the datatype and memory storage information of
NumPy
array
In NumPy, we have numpy.dtype class with the help for this,
we
can
get
the information about the data type of the array, and by using
the
itemsize attribute of this class, we can get the info about one
element
of
the
array.
The following is the coding snippet demonstrating the same:
In this example, first, we have created an array a, and then
used
the
a.dtype to get the information about the data type of array a,
which
is
int32, means the array type is a 32-bit integer. After line #8, in
this
line,
we printed the memory size in bytes for one element of this
array,
which
we got as 16 bytes. In line #10, we calculated the total memory
size
consumed by this array a. Last, we used the direct option
ndarray.nbytes to get the total memory size consumed by the
array
Creating
a.
the
NumPy
array
with
defined
datatype
If we want to create an array with a defined datatype, we must
pass
the
datatype argument with a valid NumPy type value in the np.
Array
()
function
while
creating
the
NumPy
array.
The following coding snippet are examples to create the NumPy
array
with int type
Let’s understand the examples mentioned in this coding
snippet.
Example#1: We created an array with an integer type by
passing
the
dtype=int; this will create the array with an integer type with
default
storage;
in
this
case,
it
is
a
32-bit
integer.
Example#2: If we want some defined storage size of array
elements,
we
can pass the valid datatype with storage values like int8, int 16,
and
so
on. So, in this example, we create an array with a 16-bit
integer.
Example#3: In this example, we used the character code with
storage
value (bytes) means dtype=i2, which is the same as int16, so
this
another
is
way
to
achieve
the
same.
In a similar way, we can create arrays as per need. The
following
are
the
examples to create an array with float datatype
The following is the coding snippet to demonstrate the array
creation
with boolean type:
The following is the coding snippet to demonstrate the array
creation
with String and Unicode string type
In this coding snippet, we can observe that we have just passed
the
type
only. Still, in output, we can see some numbers also along with
S
and
U.
This is the length of string which will be assigned automatically
according to the longest element of the array, which means if
we
put
some string size with S and U while creating an array, it will
truncate
the
data which have more characters that defined.
Structured
DataType
or
record
type
The structure data type is like Struct in C, or we can think of it
like
a
row
in SQL. This means it has a collection for fields that may or may
not
have the same data type, unlike the typically NumPy Array. We
can
create structured datatype using the function NumPy.dtype().
There
are
several ways to define the structured data type. One of them is
passing
the
list
of
tuples
with
(field_name,
data_type).
Syntax: struct_type = numpy.dtype([(filed1,filed1_type),
(filed2,filed2_type)…(filedn,filedn_type)])
Here, the field type will be the valid Numpy data types like
int8,int16,
float,
and
so
on.
The following is an example where we have created a
structured
data
type of employee:
In this example, we have first created the structured data type
employed,
which has three fields names, dept, and sal associated with
datatypes
S10 (String with size ten chars), S10, i4 (32-bit integer),
respectively.
Line
#5
has
a
statement
to
create
an
array
with
datatype=employee.
We
can see line #6 print the dtype, which we have defined
already.
Similarly,
if
we
multidimensional
can
do
the
same
in
the
case
of
a
array,
we have to pass the third argument shape along with the field
name
and
type.
NumPy
array
shape
manipulation
We often have to deal with resizing or reshaping the shape of
the
NumPy
array.
The following is a list of essential functions we need for daily
data
analysis
work:
Function/
method
reshape()
flat()
flatten()
ravel()
transpose()
a returned new array with a specified
shape without modifying data
flattens the array then returns the element
of a specified index
returns the one-dimentional copy of input
array
returns the one-dimentional view of input
array
transposes the axes
same as reshape(), but resize modifies the
input
resize()
Table
Description
array
on
which
this
has been applied, or modifies the referred
10.2:
array
Essential
functions
for
data
analysis
See the following coding examples to understand these
functions better:
We have shown all the examples for the previously discussed
functions;
following is the output after executing these examples
the
This snippet has the output for all the examples which we have
executed.
Inserting
and
deleting
array
element(s)
This is a common need when adding an element(s) into the
array
or
deleting
the element(s) from the existing array; the following are the
functions
to
achieve
the
same:
numpy.append()
This function returns a new array by appending the values at
the
last
of
the input array. Dimensions of the values we want to append
must
the
match
input
array;
otherwise,
it
will
give
an
error.
Syntax : numpy.append(existing_array,values,axis)
In this coding snippet, we have a 1-D array num_array, and we
append
the value 10 at the end of input array num_array, and create a
new
array
num_num_array. In the following example, let’s see how we
work
with
D arrays or array with multidimensions:
2-