Hướng dẫn python file to dataframe - tập tin python vào khung dữ liệu
Đây là cách thường ít được áp dụng vì khi làm việc chúng ta thường đọc dữ liệu từ những file dữ liệu có sẵn được lưu dưới dạng %%script echo skipping # Lưu dữ liệu sang file csv df.to_csv('BostonHousing.csv', index = False) # Lưu file excel df.to_excel('BostonHousing.xls', index = False) # Lưu dữ file json df.to_json('BostonHousing.json') #do not include index = False, index only use for table orient7 hoặc %%script echo skipping # Lưu dữ liệu sang file csv df.to_csv('BostonHousing.csv', index = False) # Lưu file excel df.to_excel('BostonHousing.xls', index = False) # Lưu dữ file json df.to_json('BostonHousing.json') #do not include index = False, index only use for table orient8. Nhưng đôi khi chúng ta cũng cần khởi tạo dataframe từ đầu chẳng hạn như bạn muốn lưu kết quả log file của chương trình vào một dataframe và save dưới dạng %%script echo skipping # Lưu dữ liệu sang file csv df.to_csv('BostonHousing.csv', index = False) # Lưu file excel df.to_excel('BostonHousing.xls', index = False) # Lưu dữ file json df.to_json('BostonHousing.json') #do not include index = False, index only use for table orient7 sau đó. Việc lưu trữ dưới dạng dataframe sẽ giúp cho bạn dễ dàng thực hiện các phép lọc, thống kê và visualize trực tiếp từ dataframe một cách dễ dàng hơn. Show
Đưới đây mình sẽ giới thiệu hai cách khởi tạo dataframe chính trực tiếp từ câu lệnh # Lựa chọn 5 dòng đầu và 5 cột đầu của df df.iloc[:5, :5]0. 2.1.1. Khởi tạo thông qua dictionary¶Về định dạng dictionary chúng ta đã được học ở chương phụ lục - dictionary. Nội dung của dictionary sẽ gồm key là tên cột và value là list giá trị của cột tương ứng. import pandas as pd from IPython.display import display pd.set_option('max_colwidth', 40) pd.set_option('precision', 5) pd.set_option('max_rows', 10) pd.set_option('max_columns', 30) dict_columns = { 'contents':['Author', 'Book', 'Target', 'No_Donation'], 'infos':['Pham Dinh Khanh', 'ML algorithms to Practice', 'Vi mot cong dong AI vung manh hon', 'Community'], 'numbers':[1993, 2021, 1, 2] } df = pd.DataFrame(dict_columns) display(df)
Hàm display của # Lựa chọn 5 dòng đầu và 5 cột đầu của df df.iloc[:5, :5]1 giúp cho DataFrame hiển thị được trên code khi run dưới dạng script file. các options của # Lựa chọn 5 dòng đầu và 5 cột đầu của df df.iloc[:5, :5]2 lần lượt có tác dụng:
Tiếp theo chúng ta sẽ khởi tạo thông qua list các dòng. 2.1.2. Khởi tạo thông qua list các dòng¶Theo cách này chúng ta sẽ truyền vào data là một list gồm các tupple mà mỗi tupple là một dòng dữ liệu. đối số # Lựa chọn 5 dòng đầu và 5 cột đầu của df df.iloc[:5, :5]7 sẽ qui định tên cột theo đúng thứ tự được qui định ở mỗi dòng. import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df
Hàm display của # Lựa chọn 5 dòng đầu và 5 cột đầu của df df.iloc[:5, :5]1 giúp cho DataFrame hiển thị được trên code khi run dưới dạng script file. các options của # Lựa chọn 5 dòng đầu và 5 cột đầu của df df.iloc[:5, :5]2 lần lượt có tác dụng: # Lựa chọn 5 dòng đầu và 5 cột đầu của df df.iloc[:5, :5] 3: Qui định chiều rộng tối đa của một cột.# Lựa chọn 5 dòng đầu và 5 cột đầu của df df.iloc[:5, :5]4: Độ chính xác của các sau dấu phảy của các cột định dạng float.
age: Tỷ lệ căn hộ được xây dựng trước năm 1940.
age
ptratio Hàm import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df00 sẽ cho ta biết định dạng và số lượng quan sát import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df01 của mỗi trường trong dataframe.
Hoặc chúng ta có thể dùng hàm import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df02 để kiểm tra định dạng dữ liệu các trường của một bảng. # Check for datatype df.dtypes crim float64 zn float64 indus float64 chas int64 nox float64 ... tax int64 ptratio float64 b float64 lstat float64 medv float64 Length: 14, dtype: object Nếu muốn kiểm tra chi tiết hơn những thống kê mô tả của dataframe như trung bình, phương sai, min, max, median của một trường dữ liệu chúng ta dùng hàm import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df03 # Thống kê mô tả dữ liệu df.describe()
2.1.4. Export to CSV, EXCEL, TXT, JSON¶Đây là câu lệnh được sử dụng khá phổ biến để lưu trữ các file dữ liệu từ dataframe sang những định dạng khác nhau. Những định dạng này sẽ cho phép chúng ta load lại dữ liệu bằng các hàm import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df04 sau đó. %%script echo skipping # Lưu dữ liệu sang file csv df.to_csv('BostonHousing.csv', index = False) # Lưu file excel df.to_excel('BostonHousing.xls', index = False) # Lưu dữ file json df.to_json('BostonHousing.json') #do not include index = False, index only use for table orient 2.2. Thao tác với dataframe¶2.2.1. Truy cập dataframe¶Chúng ta có thể truy cập dataframe theo hai cách. Truy cập theo slice index: Theo cách này chúng ta chỉ cần truyền vào index của dòng và cột và sử dụng hàm import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df05 để trích xuất ra các dòng và cột tương ứng. Cách lấy slice cho rows và columns hoàn toàn tương tự như truy cập slice index trong list. Note: import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df06 là viết tắt của indice location, tức là truy cập quan indice. # Lựa chọn 5 dòng đầu và 5 cột đầu của df df.iloc[:5, :5]
# Lựa chọn 5 dòng từ 5:10 và 2 cột từ 2:4 df.iloc[5:10, 2:4]
import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df0
nox import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df1
count Đây là cách được sử dụng phổ biến vì nó tường minh hơn. Theo cách này chúng ta sẽ truy cập các trường của dataframe bằng cách khai báo list column_names của chúng. mean import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df2
tax: Chúng ta có thể truy cập dataframe bằng cách kết hợp cả hai cách theo hướng sử dụng column names đối với cột và slice index đối với dòng: import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df3
taxptratio
count import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df4
Muốn lọc các cột theo định dạng dữ liệu thì như thế nào? Ta dùng hàm import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df15 để lọc các cột theo định dạng dữ liệu. Những định dạng chính bao gồm import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df16. Ví dụ: Bên dưới chúng ta lọc các trường có định dạng dữ liệu là import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df17. import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df5
Muốn lọc các cột theo định dạng dữ liệu thì như thế nào? Ta dùng hàm import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df15 để lọc các cột theo định dạng dữ liệu. Những định dạng chính bao gồm import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df16. Ví dụ: Bên dưới chúng ta lọc các trường có định dạng dữ liệu là import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df17. import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df6
d import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df7
e Lựa chọn các cột bắt đầu là import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df 19 thông qua hàm filter.Trong pandas thì import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df20 là làm việc với cột và import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df21 là làm việc với dòng. Giá trị của import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df22 có nghĩa là lọc các cột có chuỗi ký tự là import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df19 đứng đầu. 2.2.3. Sort dữ liệu¶ Trong nhiều trường hợp bạn sẽ cần sort dữ liệu theo chiều từ thấp lên cao hoặc từ cao xuống thấp để biết đâu là những quan sát nhỏ nhất và lớn nhất cũng như việc tạo ra một đồ thị có trend rõ ràng và thể hiện quan hệ tuyến tính giữa các biến theo trend. import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df8
Muốn lọc các cột theo định dạng dữ liệu thì như thế nào? import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df9
Muốn lọc các cột theo định dạng dữ liệu thì như thế nào?Ta dùng hàm import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df 15 để lọc các cột theo định dạng dữ liệu. Những định dạng chính bao gồm import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df 16. Ví dụ: Bên dưới chúng ta lọc các trường có định dạng dữ liệu là import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df 17.Lọc các cột theo pattern của tên cột import pandas as pd df = pd.read_csv("https://raw.githubusercontent.com/phamdinhkhanh/datasets/master/BostonHousing.csv", sep=",", header = 0, index_col = None) df.head()0 import pandas as pd df = pd.read_csv("https://raw.githubusercontent.com/phamdinhkhanh/datasets/master/BostonHousing.csv", sep=",", header = 0, index_col = None) df.head()1 Khi làm việc với dữ liệu lớn sẽ có những tình huống mà bạn bắt gặp các cột thuộc về cùng một nhóm và chúng có chung một pattern. Chẳng hạn như về age sẽ có import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df 18,… Làm thế nào để bạn lọc ra được những biến này từ dữ liệu? Chúng ta sẽ dùng hàm filter. Đây là hàm cực kỳ tiện ích khi lọc cột từ những bộ dữ liệu lớn mà bạn sẽ thường xuyên sử dụng sau này.name import pandas as pd df = pd.read_csv("https://raw.githubusercontent.com/phamdinhkhanh/datasets/master/BostonHousing.csv", sep=",", header = 0, index_col = None) df.head()2
Ta dùng hàm import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df 15 để lọc các cột theo định dạng dữ liệu. Những định dạng chính bao gồm import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df 16. Ví dụ: Bên dưới chúng ta lọc các trường có định dạng dữ liệu là import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df 17.Lọc các cột theo pattern của tên cột import pandas as pd df = pd.read_csv("https://raw.githubusercontent.com/phamdinhkhanh/datasets/master/BostonHousing.csv", sep=",", header = 0, index_col = None) df.head()3 import pandas as pd df = pd.read_csv("https://raw.githubusercontent.com/phamdinhkhanh/datasets/master/BostonHousing.csv", sep=",", header = 0, index_col = None) df.head()4 Trường hợp muốn xác định tỷ lệ phần trăm luỹ kế của các ngưỡng phân chia ta có thể khai báo q là list gồm các ngưỡng luỹ kế. Ví dụ bên dưới ta muốn chia làm ba khoảng giá trị, mỗi khoảng chiếm 33% thì ta khai báo ngưỡng luỹ kế import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df32luỹ kế của các ngưỡng phân chia ta có thể khai báo q là list gồm các ngưỡng luỹ kế. Ví dụ bên dưới ta muốn chia làm ba khoảng giá trị, mỗi khoảng chiếm 33% thì ta khai báo ngưỡng luỹ kế import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df32 2.2.4.4. Apply¶Apply sẽ giúp ta biến đổi giá trị của một trường theo một hàm số xác định trước. Hàm số biến đổi được áp dụng trong apply sẽ là một hàm import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df33. Hàm lambda là một khái niệm rất quan trọng trong python, hàm số này có cú pháp dạng import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df34. Phân tích kỹ hơn thì chúng ta thấy nó không có return. Điều này là phù hợp với ý nghĩa của hàm lambda vì nó không yêu cầu gía trị trả về ngay. Thực tế nó giống như một lời hứa sẽ thực hiện hàm đó tại thời điểm áp dụng một cách ngầm định bên trong một hàm khác (ở đây là hàm apply). Ví dụ bên dưới ta muốn nhân đôi giá trị của tax thì có thể sử dụng hàm apply với lambda như sau: import pandas as pd df = pd.read_csv("https://raw.githubusercontent.com/phamdinhkhanh/datasets/master/BostonHousing.csv", sep=",", header = 0, index_col = None) df.head()5 import pandas as pd df = pd.read_csv("https://raw.githubusercontent.com/phamdinhkhanh/datasets/master/BostonHousing.csv", sep=",", header = 0, index_col = None) df.head()6 Ta cũng có thể áp dụng cho nhiều trường một lúc. Khi đó cần khai báo import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df20 để biết rằng ta đang áp dụng trên từng cột, nếu axis=0 thì sẽ áp dụng trên từng dòng. import pandas as pd df = pd.read_csv("https://raw.githubusercontent.com/phamdinhkhanh/datasets/master/BostonHousing.csv", sep=",", header = 0, index_col = None) df.head()7
2.2.4.5. Map¶Map là hàm giúp biến đổi giá trị của một biến sang giá trị mới dựa trên dictionary mà chúng ta áp dụng. Giá trị cũ sẽ là key và giá trị mới sẽ là value. Bên dưới ta sẽ map các giá trị của trường import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df36 sang các giá trị tiếng Việt. import pandas as pd df = pd.read_csv("https://raw.githubusercontent.com/phamdinhkhanh/datasets/master/BostonHousing.csv", sep=",", header = 0, index_col = None) df.head()8 import pandas as pd df = pd.read_csv("https://raw.githubusercontent.com/phamdinhkhanh/datasets/master/BostonHousing.csv", sep=",", header = 0, index_col = None) df.head()9 2.2.5. Biểu đồ matplotlib trên pandas¶Chúng ta có thể nói rằng pandas rất mạnh vì nó đã wrap dường như toàn bộ các đồ thị cơ bản của matplotlib vào bên trong các hàm thành phần của pandas column. Do đó việc visualize trở nên vô cùng ngắn gọn, thậm chí là chỉ trên một dòng. Bên dưới chúng ta sẽ cùng lướt qua nhanh các đồ thị cơ bản khi visualize trên import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df37. Biến được áp dụng đồng nhất cho các đồ thị là import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df38. 1. biểu đồ line 2. Biểu đồ line kết hợp với point 0 3. Biểu đồ barchart Biều đồ này được dùng phù hợp khi chúng ta muốn so sánh chênh lệch giữa các nhóm về mặt giá trị tuyệt đối. 1 2 Ở đây ta sẽ phải dùng thêm hàm groupby để tạo thành bảng thống kê tổng thuế theo import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df39 rồi mới vẽ biểu đồ. Khi quen thuộc bạn có thể viết gọn hai câu lệnh lại thành một line như sau: 3 2 4. Biểu đồ pie Đây là biểu đồ dùng để thể hiện giá trị phần trăm. Phù hợp khi so sánh giá trị tương đối giữa các nhóm. 5 6 5. Biểu đồ boxplot Biểu đồ boxplot sẽ được sử dụng để quan sát phân phối của biến đối với các giá trị min, max và các ngưỡng phân vị 25%, 50%, 75%. Căn cứ vào boxplot ta có thể biết được khoảng biến thiên của biến rộng hay hẹp, biến phân phối lệch trái hay phải. 7 6. Biểu đồ area Biểu đồ area cho ta biết diện tích nằm dưới đường biểu diễn và trên trục hoành. 8 2 2.3. Reshape dataframe trên pandas¶2.3.1. Melt¶Hàm melt là hàm được lấy ý tưởng từ ngôn ngữ R. Hàm này sẽ làm cho bảng của chúng ta trở nên bớt cồng kềnh hơn bằng cách rút gọn nhiều measurements thành hai cột variable và value trong đó cột variable qui định loại measurement và value là giá trị của measurement. Bảng của bạn sẽ có ít cột hơn đáng kể nên trông giống như các cột measurement đang bị tan chảy vậy. Do đó nó có tên gọi là melt. Bạn sẽ dễ hình dung hơn những gì mình nói thông qua ví dụ bên dưới. Giả sử bảng của mình gồm Ho, Ten là các dimensions và import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df40 là những measurements. # Check for datatype df.dtypes0
Ta nhận thấy import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df41 là những dimension, bây giờ ta sẽ giữ nguyên những trường này và làm tan chảy các cột.
Dong Ta nhận thấy import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df41 là những dimension, bây giờ ta sẽ giữ nguyên những trường này và làm tan chảy các cột. variablevalue
Ta thấy hàm này sẽ tìm toàn bộ các biến là category (có định dạng trường là import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df54) và tự động trải phẳng chúng. Khi đó các cột mới được tạo thành chính là import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df55, import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df56 là những nhãn thuộc biến import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df46. Giá trị của những trường này bằng 0 hoặc 1.toàn bộ các biến là category (có định dạng trường là import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df54) và tự động trải phẳng chúng. Khi đó các cột mới được tạo thành chính là import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df55, import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df56 là những nhãn thuộc biến import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df46. Giá trị của những trường này bằng 0 hoặc 1. Mặc dù có cú pháp cực kì đơn giản nhưng hàm import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df53 lại cực kì hữu ích đối với data scientist khi xây dựng mô hình mà bạn cần ghi nhớ. 2.4. Thống kê theo nhóm trên pandas¶Khi làm việc với dữ liệu bảng chúng ta thường xuyên phải thống kê dữ liệu theo các nhóm để bắt dữ liệu tạo ra những thông tin insight hữu ích cho phân tích và ra quyết định. Ngoài ra những feature tốt, có sức mạnh phân loại và dự báo cao có thể được tạo thành từ việc thống kê dữ liệu theo nhóm. Quá trình thống kê và phân tích dữ liệu mặc dù tốn kém về mặt thời gian nhưng lại rất quan trọng đối với mô hình. Vì vậy chúng ta cần thực hiện chúng kỹ lưỡng và cần kết hợp giữa kỹ năng thống kê và kinh nghiệm thực tiễn. Ở mục 5 này chúng ta sẽ làm quen với hai câu lệnh kinh điển trong pandas được sử dụng nhiều trong thống kê theo nhóm trên pandas đó là import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df59 và import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df60. 2.4.1. df.groupby()¶groupby là câu lệnh cho phép bạn áp dụng những hàm số trên measurements dựa trên việc phân nhóm dữ liệu theo các dimensions. Nếu bạn chưa hiểu về khái niệm measurement và dimension thì mình có thể giải thích đơn giản là: measurement là những biến có thể cộng trừ nhân chia và đo đếm được còn dimension là những biến dùng để phân nhóm dữ liệu. Ví dụ chiều cao là một measurement có thể đo theo dimension là giới tính gồm các nhóm nam/nữ. Cú pháp của hàm import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df59 khá đơn giản: # Check for datatype df.dtypes1 Chúng ta cần xác định các chiều dimension trong import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df62. Phía sau import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df63 là một list các measurements mà ta cần áp dụng hàm lên trên những trường này. # Check for datatype df.dtypes2 # Check for datatype df.dtypes3 Theo cách trên thì ta chỉ áp dụng được với những hàm tính toán như import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df64 có sẵn trong dataframe. Nếu muốn sử dụng import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df63 cho mọi biến đổi hàm chúng ta có thể dùng hàm import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df66 trong import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df67. # Check for datatype df.dtypes4 # Check for datatype df.dtypes3 Nếu muốn áp dụng tính toán cho nhiều measurements một lúc thì truyền vào một list các measurements. Chẳng hạn bên dưới ta truyền vào một list gồm import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df68 # Check for datatype df.dtypes6
Chúng ta cũng có thể tự định nghĩa các hàm được tuỳ biến theo ý muốn: # Check for datatype df.dtypes7 # Check for datatype df.dtypes8 Hoặc group theo nhiều chiều dữ liệu. Khi đó phải truyền vào import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df63 một list các dimension. # Check for datatype df.dtypes9 crim float64 zn float64 indus float64 chas int64 nox float64 ... tax int64 ptratio float64 b float64 lstat float64 medv float64 Length: 14, dtype: object0 Ưu điểm của import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df63 đó là nhanh gọn, dễ hiểu. Nhưng nhược điểm của import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df63 đó là chúng ta chỉ có thể áp dụng cùng một biến đổi hàm số cho mọi measurements. Ở import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df72 bạn có thể tuỳ biến sâu hơn từng hàm đối với từng measurement nhưng cú pháp sẽ phức tạp hơn một chút. 2.4.2. Pivotable¶Pivot table là một công thức có ứng dụng rất quan trọng trong pandas. Nó giúp cho chúng ta thực hiện các thống kê trên các biến measurement theo các chiều dimension. Bạn sẽ hình dung ra cách áp dụng của import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df73 thông qua ví dụ bên dưới. crim float64 zn float64 indus float64 chas int64 nox float64 ... tax int64 ptratio float64 b float64 lstat float64 medv float64 Length: 14, dtype: object1
Ưu điểm của import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df63 đó là nhanh gọn, dễ hiểu. Nhưng nhược điểm của import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df63 đó là chúng ta chỉ có thể áp dụng cùng một biến đổi hàm số cho mọi measurements. Ở import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df72 bạn có thể tuỳ biến sâu hơn từng hàm đối với từng measurement nhưng cú pháp sẽ phức tạp hơn một chút. 2.4.2. Pivotable¶ Pivot table là một công thức có ứng dụng rất quan trọng trong pandas. Nó giúp cho chúng ta thực hiện các thống kê trên các biến measurement theo các chiều dimension. Bạn sẽ hình dung ra cách áp dụng của import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df73 thông qua ví dụ bên dưới.
Các dòng lại được phân nhóm theo chỉ số mức độ tiếp cận đường cao tốc Như vậy ta có thể hình dung được trong công thức của pivot_table, các đối số của nó có ý nghĩa như sau: crim float64 zn float64 indus float64 chas int64 nox float64 ... tax int64 ptratio float64 b float64 lstat float64 medv float64 Length: 14, dtype: object2
Bảng của chúng ta đã tăng gấp đôi số cột. Dòng đầu tiên của bảng là import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df82, import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df38 là những thông tin ứng với từng measurement. Bạn thấy đó, import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df87 hoàn toàn đơn giản và rất hiệu quả phải không nào? 2.5. Join, Merge và Concatenate bảng¶Những doanh nghiệp lớn thường tổ chức cơ sở dữ liệu dưới dạng những bảng dữ liệu có quan hệ. Những bảng này được liên kết với nhau bởi key dưới những quan hệ dữ liệu như one-to-one, many-to-one hoặc one-to-many. Những kiến trúc phổ biến trong data warehouse như import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df88 và import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df89 sẽ giúp cho chúng ta nhanh chóng join các bảng lại với nhau để tạo ra những bảng raw data tổng hợp phục vụ cho các nhu cầu phân tích, thống kê và xây dựng mô hình. Ngoài ngôn ngữ SQL là công cụ chính để làm việc với những hệ cơ sở dữ liệu có quan hệ, Data scientist cũng cần nắm vững những kỹ năng liên kết join, merge và concatenate bảng trên pandas mà thông qua chương này mình sẽ giới thiệu tới các bạn. 2.5.1. Các kiểu join¶Chúng ta có 4 kiểu join chính là import pandas as pd records = [('Author', 'Pham Dinh Khanh', 1993), ('Book', 'ML algorithms to Practice', 2021), ('Target', 'Vi mot cong dong AI vung manh hon', 1), ('No_Donation', 'Community', 2)] # Khởi tạo DataFrame df = pd.DataFrame(data = records, columns = ['contents', 'infos', 'numbers']) df90 được thể hiện qua biểu đồ venn bên dưới: Chúng ta có hai bảng bên trái và bên phải với những phần thông tin chung (giao nhau giữa hai vòng tròn) và riêng. Phần diện tích màu xanh lá cây là Kết quả của phép join. Chúng ta có thể hình dung kết quả của phép join đó là:
Bên dưới chúng ta cùng thực hành join. crim float64 zn float64 indus float64 chas int64 nox float64 ... tax int64 ptratio float64 b float64 lstat float64 medv float64 Length: 14, dtype: object3
crim float64 zn float64 indus float64 chas int64 nox float64 ... tax int64 ptratio float64 b float64 lstat float64 medv float64 Length: 14, dtype: object4
Doan Thu HaCan Tho crim float64 zn float64 indus float64 chas int64 nox float64 ... tax int64 ptratio float64 b float64 lstat float64 medv float64 Length: 14, dtype: object5 Math
right: bảng bên phải how: Phương pháp join gồm crim float64 zn float64 indus float64 chas int64 nox float64 ... tax int64 ptratio float64 b float64 lstat float64 medv float64 Length: 14, dtype: object6
Tran Quang Nghia Những ID xuất hiện ở bảng bên trái sẽ được lựa chọn. crim float64 zn float64 indus float64 chas int64 nox float64 ... tax int64 ptratio float64 b float64 lstat float64 medv float64 Length: 14, dtype: object7
Math Những ID xuất hiện ở bảng bên phải sẽ được lựa chọn. crim float64 zn float64 indus float64 chas int64 nox float64 ... tax int64 ptratio float64 b float64 lstat float64 medv float64 Length: 14, dtype: object8
Doan Thu Ha Tất cả ID xuất hiện ở bảng bên trái hoặc bảng bên phải sẽ được lựa chọn. crim float64 zn float64 indus float64 chas int64 nox float64 ... tax int64 ptratio float64 b float64 lstat float64 medv float64 Length: 14, dtype: object9
Can ThoQuang Nam # Thống kê mô tả dữ liệu df.describe()0
Can Tho Quang Nam # Thống kê mô tả dữ liệu df.describe()1
# Thống kê mô tả dữ liệu df.describe()2 Doan Thu HaCan Tho Quang Nam # Thống kê mô tả dữ liệu df.describe()3 Nghe An
Age Math Physic # Thống kê mô tả dữ liệu df.describe()4
Can Tho # Thống kê mô tả dữ liệu df.describe()5
Can Tho Quang Nam # Thống kê mô tả dữ liệu df.describe()6
Can Tho # Thống kê mô tả dữ liệu df.describe()7
Can Tho # Thống kê mô tả dữ liệu df.describe()8
Doan Thu HaCan Tho Theo dòng. # Thống kê mô tả dữ liệu df.describe()9
Doan Thu Ha Can Tho %%script echo skipping # Lưu dữ liệu sang file csv df.to_csv('BostonHousing.csv', index = False) # Lưu file excel df.to_excel('BostonHousing.xls', index = False) # Lưu dữ file json df.to_json('BostonHousing.json') #do not include index = False, index only use for table orient0
NganhInterest d v
Đây là một pakage cho phép chúng ta kết nối và truy vấn trên những dữ liệu SQL một cách trực tiếp theo mô hình server-client side. Chúng ta sẽ phải khai báo một số thông tin quan trọng để khởi tạo kết nối như:: Ở phần ví dụ thực hành liên quan tới SQL thì mỗi máy sẽ có một cấu hình khác nhau. Để thực hành được code bên dưới trước tiên máy tính của bạn cần cài SQL Server và có sẵn những database trong server. Tên server là gì? Tên database trong server cần truy vấn. %%script echo skipping # Lưu dữ liệu sang file csv df.to_csv('BostonHousing.csv', index = False) # Lưu file excel df.to_excel('BostonHousing.xls', index = False) # Lưu dữ file json df.to_json('BostonHousing.json') #do not include index = False, index only use for table orient1 port: Cổng kết nối, thường mặc định của MSSQL là 1443. %%script echo skipping # Lưu dữ liệu sang file csv df.to_csv('BostonHousing.csv', index = False) # Lưu file excel df.to_excel('BostonHousing.xls', index = False) # Lưu dữ file json df.to_json('BostonHousing.json') #do not include index = False, index only use for table orient2 username: Tên user. %%script echo skipping # Lưu dữ liệu sang file csv df.to_csv('BostonHousing.csv', index = False) # Lưu file excel df.to_excel('BostonHousing.xls', index = False) # Lưu dữ file json df.to_json('BostonHousing.json') #do not include index = False, index only use for table orient3 password: Mật khẩu truy cập. Chú ý: Ở phần ví dụ thực hành liên quan tới SQL thì mỗi máy sẽ có một cấu hình khác nhau. Để thực hành được code bên dưới trước tiên máy tính của bạn cần cài SQL Server và có sẵn những database trong server. %%script echo skipping # Lưu dữ liệu sang file csv df.to_csv('BostonHousing.csv', index = False) # Lưu file excel df.to_excel('BostonHousing.xls', index = False) # Lưu dữ file json df.to_json('BostonHousing.json') #do not include index = False, index only use for table orient4 Bạn sẽ cần khai báo đúng các trường cấu hình truy cập trong import pandas as pd df = pd.read_csv("https://raw.githubusercontent.com/phamdinhkhanh/datasets/master/BostonHousing.csv", sep=",", header = 0, index_col = None) df.head()11 và tên bảng tại import pandas as pd df = pd.read_csv("https://raw.githubusercontent.com/phamdinhkhanh/datasets/master/BostonHousing.csv", sep=",", header = 0, index_col = None) df.head()12. %%script echo skipping # Lưu dữ liệu sang file csv df.to_csv('BostonHousing.csv', index = False) # Lưu file excel df.to_excel('BostonHousing.xls', index = False) # Lưu dữ file json df.to_json('BostonHousing.json') #do not include index = False, index only use for table orient5 Nếu bạn thực hành bị lỗi các ví dụ tại mục 3 này, hãy tạm thời bỏ qua chúng. Sau khi sử dụng connection thì chúng ta nhớ đóng lại connection để giải phóng memory và port. %%script echo skipping # Lưu dữ liệu sang file csv df.to_csv('BostonHousing.csv', index = False) # Lưu file excel df.to_excel('BostonHousing.xls', index = False) # Lưu dữ file json df.to_json('BostonHousing.json') #do not include index = False, index only use for table orient6 Chúng ta cũng có thể thực thi các lệnh của SQL thông qua engine SQL mà chúng ta đã khởi tạo. Kết quả sẽ được truy vấn và tính toán trực tiếp từ server trả về như câu lệnh ta yêu cầu.pyodbc
Cách đọc, lưu và khởi tạo dataframe Thao tác dữ liệu trên dataframe: truy cập bảng, sort, filter và các hàm cơ bản trên dataframe. Thay đổi shape của bảng qua melt và dummy.Thống kê theo groupby và pivot_table.
|