Professional Documents
Culture Documents
2.2. Thu Vien Pandas
2.2. Thu Vien Pandas
2.2. Thu Vien Pandas
DỮ LIỆU
Chương 2
NGÔN NGỮ
LẬP TRÌNH
THƯ VIỆN
Nội dung
Đặc điểm:
- Đồng nhất dữ liệu
- Kích thước có thể thay đổi
- Giá trị có thể thay đổi
3 Cấu trúc dữ liệu trong Pandas
Parameters:
data: dữ liệu từ ndarray, list, constants
index: Index values must be unique and hashable, same length as data..
dtype: dtype là loại dữ liệu. Nếu không có thì tự suy ra
copy: Copy data. Default False
3 Cấu trúc dữ liệu trong Pandas
DataFrame
- Dataframe là cấu trúc dữ liệu 2
chiều.
- DataFrame được sử dụng để lưu
trữ dữ liệu theo dạng bảng, bao
gồm hàng và cột.
Đặc điểm:
- Các cột có thể lưu các kiểu dữ liệu khác nhau
- Kích thước có thể thay đổi
- Có tên dòng, tên cột. Nếu không đặt thì mặc định bắt đầu từ 0
- Có thể thực hiện các phép toán trên dòng hoặc cột.
3 Cấu trúc dữ liệu trong Pandas
Ví dụ
4 Hàm cơ bản trong Pandas
Tạo DataFrame
Cú pháp: pandas.DataFrame(data, index, columns, dtype, copy)
Data Syntax Explained
Empty pd.DataFrame() Create an empty dataframe.
Numpy arr = np.array([1,2,3,4,5]) Create an dataframe from ndarry
arrary df = pd.DataFrame(arr) ‘arr’.
List data = [1,2,3,4,5] Create an dataframe from a list
df = pd.DataFrame(data) ‘data’.
List of List data = [['Alex',10],['Bob',12],['Clarke',13]] Create an dataframe from list that
df = pd.DataFrame(data,columns=['Name','Age']) contains 3 another lists.
Dict of Lists data = { 'Name':['Tom', 'Jack', 'Steve', 'Ricky'], Create an dataframe from a
'Age':[28,34,29,42] } dictionary that contains 2 lists.
df = pd.DataFrame(data)
DataFrame pd.DataFrame(df, columns = ['one','three']) Create an dataframe from another
dataframe
4 Hàm cơ bản trong Pandas
Tạo dataframe từ dữ liệu có sẵn
4 Hàm cơ bản trong Pandas
Tạo dataframe từ file .CSV, .TXT file
4 Hàm cơ bản trong Pandas
Tạo dataframe từ file .CSV, .TXT file
Cú pháp: pandas.read_csv(data_path, sep, usecol, skiprows, encoding)
Các tham số:
data_path: the path to imported file.
sep: the sign between columns
usecol : Only comlumns in parameter are imported to dataframe.
skiprows : the amount of row will be not imported to dataframe.
encoding: encoding the text on file.
4 Hàm cơ bản trong Pandas
Import DataFrame from Excel file
Syntax: dataframe.read_excel(‘Excel_file.xlsx')
Ví dụ:
import sqlite3
import pandas as pd
conn = sqlite3.connect('test_database’)
sql_query = pd.read_sql_query (''' SELECT * FROM products ''', conn)
df = pd.DataFrame(sql_query, columns=['product_id','product_name'])
print (df)
4 Hàm cơ bản trong Pandas
Truy xuất dòng
Cú pháp:
dataframe.loc[row_indexer:column_indexer]
dataframe.iloc[row_indexer:column_indexer]
Cú pháp:
dataframe.to_excel(excel_writer, sheet_name='Sheet1', columns=None, header=True, index=True)
4 Hàm cơ bản trong Pandas
Một số phương thức trong dataframe
Attribute Syntax Explained
Index df.index Show the rows name in the dataframe
Columns df. columns Show the columns name in the dataframe
Axes df.axes Show the rows and columns name in the
dataframe
Dtypes df. dtypes Show the data type of each column
Size df. size Show the number of rows and columns
Shape df. shape Show the number of rows and columns
Count df.count(0) #count rows count of the items in the DataFrame. By default, it
df.count(1) # count columns gives the count of the rows
Isna df.isna() Find if there any emptiness of the DataFrame
df.isnull()
4 Hàm cơ bản trong Pandas
Ví dụ
5 Hàm cơ bản xử lý dữ liệu
Ví dụ
5 Hàm cơ bản xử lý dữ liệu
GroupBy
5 Hàm cơ bản xử lý dữ liệu
Cú pháp:
pandas.groupby(by=None, axis=0, level=None, as_index=True, sort=True)
DataFrame 2
5 Hàm cơ bản xử lý dữ liệu
objs Dataframe
axis Column = 1, Row = 0
join Inner or outer
ignore_index Reindex if value = False, default is True
5 Hàm cơ bản xử lý dữ liệu
Các hàm thống kê
Standard Deviation
5 Hàm cơ bản xử lý dữ liệu
Function Explained Example
Min Tìm giá trị min df.min()
Max Tìm giá trị max df.max()
Mean Tính giá trị trung bình df.mean()
Median Tính giá trị trung vị df.median()
Count Đếm các giá trị khác null df.count()
Correlation Tìm các giá trị tương quan df.corr()
Standard Deviation Tính độ lệch chuẩn df.std()
Value count Đếm số lượng của các giá trị duy nhất df.value_counts()
Mode Trả về giá trị xuất hiện nhiều nhất df.mode()
Unique Trả về các giá trị duy nhất df.unique()
5 Hàm cơ bản xử lý dữ liệu
Một số hàm xử lý văn bản
5 Hàm cơ bản xử lý dữ liệu
Hàm Ý nghĩa
str.lower() Chuyển chuỗi str thành ký tự thường
str.upper() Chuyển chuỗi str thành ký tự hoa
str.title() Chuyển thành chữ hoa ở đầu mỗi chữ
len(string) Lấy chiều dài của chuỗi string
str.strip() Xóa khoảng trắng ở đầu và cuối chuỗi str
str.split(' ') Tách chuỗi str thành các ký tự. Khoảng tách phụ thuộc vào
ký tự trong ‘ ‘
str.get_dummies() Chuyển đổi dữ liệu category thành biến giả (One-Hot
Encoding)
str.replace(a,b) Thay đổi giá trị a thành b
5 Hàm cơ bản xử lý dữ liệu
Ví dụ: Thay đổi giá trị “F” thành “Nữ”
5 Hàm cơ bản xử lý dữ liệu
Ví dụ 2
Ví dụ 3
5 Hàm cơ bản xử lý dữ liệu
Một số hàm cơ bản xử lý dữ liệu
Filter/Groupby
df[df[col] > 0.5] | # Hiển thị những dòng mà cột col > 0.5
df[(df[col] > 0.5) & (df[col] < 0.7)] # Hiển thị những dòng mà col từ 0.5-0.7
df.sort_values(col1) # Sắp xếp dữ liệu cột col1 tăng dần
df.sort_values(col2,ascending=False) # Sắp xếp dữ liệu cột col2 giảm dần
df.groupby(col) # Gom nhóm cột col
df.groupby([col1,col2]) # Gom nhóm 2 cột col1 và col2
5 Hàm cơ bản xử lý dữ liệu
Làm sạch dữ liệu
df.columns = ['a','b','c’] # Đổi tên cột
df.rename(columns = {‘a’:A’}) # Đổi tên cột
df.isnull() # Kiểm tra giá trị rỗng
df.notnull() # Ngược lại hàm df.isnull()
df.dropna() # Xóa các dòng có chứa giá trị rỗng
df.dropna(axis=1) # Xóa các cột có giá trị rỗng
df.drop_duplicates() # Xóa các dòng có giá trị trùng
df.fillna(x) # Điền giá trị x vào vị trí null
s.fillna(s.mean()) # Điền giá trị mean vào vị trí nulll
s.astype(float) # Chuyển kiểu dữ liệu của series thành float
s.replace(1,'one') # Thay đổi giá trị ‘1’ thành 'one'
s.replace([1,3],['one','three’]) # Thay đổi 1 thành 'one’ và 3 thành 'three'
5 Hàm cơ bản xử lý dữ liệu
Ví dụ thay đổi tên cột của dataframe data