-
Tuần 1 - Ngày 10 tháng 7 năm 2019
- Giới thiệu về khóa học
- Hướng dẫn viết chương trình Python trên web
- Hướng dẫn sử dụng PyCharm
- Tổng quan về Python
- Kỹ năng sử dụng Google search
- Viết tài liệu kỹ thuật dùng Markdown
- Hàm xây dựng sẵn trong Python – math và random
- Cài đặt các công thức toán cơ bản
- Xây dựng hàm trong python
- Điều kiện if-else
- Những lỗi thường gặp trong Python
- Reading assignment
-
Tuần 2 - Ngày 17 tháng 7 năm 2019
-
Tuần 3 - Ngày 24 tháng 7 năm 2019
-
Tuần 4 - Ngày 31 tháng 7 năm 2019
-
Tuần 5 - Ngày 7 tháng 8 năm 2019
-
Advanced Python
-
Tuần 6 - Ngày 14 tháng 8 năm 2019
-
Tuần 7 - Ngày 28 tháng 8 năm 2019
-
Tuần 8
-
Tuần 9
Pandas cơ bản
Giới thiệu pandas:
- Pandas là một package để thao tác và phân tích dữ liệu trong Python. Pandas kết hợp hai cấu trúc dữ liệu bổ sung vào Python, cụ thể là Pandas Series và Pandas DataFrame. Các cấu trúc dữ liệu này cho phép chúng ta làm việc với dữ liệu có nhãn và quan hệ một cách dễ dàng và trực quan.
- Trước khi xem bài về Pandas các bạn nên xem trước Numpy nhé. và bài viết này chỉ ở mức độ cho các bạn làm quen với Pandas.
- Tại sao lại dùng Pandas? Thành công gần đây của machine learning(ML) là do lượng dữ liệu khổng lồ để train các thuật toán. Nhưng vấn đề ở đây các bộ dữ liệu lớn thường chứa các giá trị ngoại lệ, không chính xác hay phù hợp với thuật toán của bạn làm nó hoạt động không tốt. Do đó, 1 bước quan trọng trong ML là xem xét dữ liệu và đảm bảo nó phù hợp với thuật toán của bạn, và đó cũng là nơi cần dùng Pandas.
- Pandas series và DataFrame được thiết kế để phân tích thao tác dữ liệu nhanh, cũng như linh hoạt và dể sử dụng.
Khởi tạo và một số thao tác cơ bản:
#import Pandas import pandas as pd
- Bạn có thể tạo Pandas Series bằng cách dùng lệnh
pd.series(data,index)
, trong đóindex
là chỉ mục, data là giá trị tại chỉ mục đó. - Ở đây mình dùng tên của các loại hoa quả và số lượng được mua để demo.
# import pandas import pandas as pd #tạo pd series fruits = pd.Series(data = [30, 6, 'Yes', 'No'], index = ['mango', 'apple', 'pineaple', 'orange']) print(fruits)
Kết quả
- Các bạn có thể thấy index(chỉ mục) được show ở cột đầu tiên, và data show ở cột thứ 2. Ở đây chúng ta không xác định chỉ mục của data là 0, 1, 2, 3.. vv, mà là mango, apples, pineaple và orange.
- Lưu ý: data của chúng ta chứa cả số và string
- Pandas có một số thuộc tính cho phép ta lấy thông tin từ Series như sau import pandas
import pandas as pd #tạo pd series fruits = pd.Series(data = [30, 6, 'Yes', 'No'], index = ['mango', 'apple', 'pineaple', 'orange']) #show độ dài, ở đây chỉ có 1 chiều nên kết quả trả về (4,) print('\n Series has shape:', fruits.shape) #ndim để xác định nó là pandas Series(1) hay DataFranme(2) print('\n Series has dimension:', fruits.ndim) # trả về size của Series print('\n Series has a total of', fruits.size, 'elements') #check xem có mango không x = 'mango' in fruits print('\n Is mango available?: ', x)
Kết quả
Cách Truy cập và thao tác với các thành phần trong Pandas Series
Có 2 cách để truy cập đến phần tử trong Pandas Series:
- Dùng nhãn chỉ mục(index label)
- Chỉ số(numerical indices).
Để phân biệt đang dùng index label hay numerical indices thì Pandas Series có 2 thuộc tính .loc
(dùng cho index label) và .iloc
(dùng cho numerical indices).
# import pandas import pandas as pd #tạo pd series fruits = pd.Series(data = [30, 6, 'Yes', 'No'], index = ['mango', 'apple', 'pineaple', 'orange']) # sử dụng một nhãn chỉ mục duy nhất print('\n How many apples do we need to buy:', fruits['apple']) # chúng ta có thể truy cập nhiều nhãn chỉ mục print('\n Do we need orange and apples:\n', fruits[['orange', 'apple']]) # chúng tôi sử dụng loc để truy cập nhiều nhãn chỉ mục print('\n How many mango and apples do we need to buy:\n', fruits.loc[['mango', 'apple']]) # Chúng ta truy cập các phần tử trong fruits bằng các chỉ số bằng số: print('\n How many eggs and apples do we need to buy:\n', fruits[[0, 1]]) # Chúng ta sử dụng một chỉ số số âm print('\n Do we need orange:\n', fruits[[-1]]) # Chúng tôi sử dụng một chỉ số số duy nhất print('\n How many mangos do we need to buy:', fruits[0]) # chúng tôi sử dụng iloc để truy cập nhiều chỉ số print('\n Do we need mangos and apples:\n', fruits.iloc[[1, 2]])
Kết quả
Chúng ta có thể thay đổi các phẩn tử như sau:
# import pandas import pandas as pd #tạo pd series fruits = pd.Series(data = [30, 6, 'Yes', 'No'], index = ['mango', 'apple', 'pineaple', 'orange']) # đổi số lượng mango fruits['mango'] = 20 print('fruits:\n',fruits)
Kết quả
Chúng ta có thể xóa 1 item bằng cách sử dụng .drop(). Lưu ý dùng keyword inplace = True. Nếu không dùng inplace = True kết quả sẽ không được xóa.
# import pandas import pandas as pd #tạo pd series fruits = pd.Series(data = [30, 6, 'Yes', 'No'], index = ['mango', 'apple', 'pineaple', 'orange']) fruits.drop('apple', inplace = True) print('fruits:\n',fruits)
Kết quả
Phép toán số học trên Pandas Series
Các bạn xem qua ví dụ:
# import pandas import pandas as pd # tạo 1 Series mới fruits= pd.Series(data = [10, 6, 3,], index = ['apples', 'oranges', 'bananas']) # print Series mới tạo ra print(fruits)
Kết quả
# import pandas import pandas as pd # tạo 1 Series mới fruits= pd.Series(data = [10, 6, 3,], index = ['apples', 'oranges', 'bananas']) print('Original grocery list of fruits:\n ', fruits) # We add 2 to each item in fruits print('\n fruits + 2:\n', fruits + 2) # We subtract 2 to each item in fruits print('\n fruits - 2:\n', fruits - 2) # We multiply each item in fruits by 2 print('\n fruits * 2:\n', fruits * 2) # We divide each item in fruits by 2 print('\n fruits / 2:\n', fruits / 2)
Kết quả
Bạn cũng có thể dùng các hàm toán học từ Numpy cho các phần tử của Pandas
import numpy as np import pandas as pd # tạo 1 Series fruits= pd.Series(data = [10, 6, 3,], index = ['apples', 'oranges', 'bananas']) # We print fruits for reference print('Original grocery list of fruits:\n', fruits) # tính e^x, với x là các phần tử của fruits print('\n EXP(X) = \n', np.exp(fruits)) # tính căn bậc 2 print('\n SQRT(X) =\n', np.sqrt(fruits)) # tính x^2, với x là phần tử của fruits print('\n POW(X,2) =\n',np.power(fruits,2))
Kết quả
Theo cách trên thì khá đơn giản. Đoạn code trên mình áp dụng cho toàn bộ Series fruits, nếu các bạn muốn các phép toán chỉ áp dụng cho 1 phần tử nào đó thì chỉ cần thay cả fruits bằng truy cập đến một vài phần tử xác định mà bạn muốn. ví dụ:
# import pandas import pandas as pd # tạo 1 Series fruits= pd.Series(data = [10, 6, 3,], index = ['apples', 'oranges', 'bananas']) # We add 2 only to the bananas print('Amount of oranges + 2 = ', fruits['oranges'] + 2)
Kết quả
Tiếp theo chúng ta sẽ đến phần DataFrame.
Pandas DataFrame
- DataFrame là gì?
- DataFrame(DF) là cấu trúc dữ liệu 2 chiều, với hàng và cột được dán nhãn. Cách sử dụng DF cũng khá giống với excel, DF tương tự như excel vậy, DF là 1 bảng lưu trữ dữ liệu.
- Có 2 cách để tạo 1 DF:
Cách 1: tạo thủ công
Cách 2: load dữ liệu từ data file (thường là file csv).
- Bây giờ ta bắt đầu thử tạo thủ công qua ví dụ cho để hiểu hơn về DF
Cách 1: Tạo thủ công DataFrame
note: ở phần này mình giữ nguyên comment là tiếng anh, và một số đoạn code mình sẽ giải thích tiếng việt.
# import pandas import pandas as pd # We create a dictionary of Pandas Series items = {'Bob' : pd.Series(data = [245, 25, 55], index = ['bike', 'pants', 'watch']), 'Alice' : pd.Series(data = [40, 110, 500, 45], index = ['book', 'glasses', 'bike', 'pants'])} # print the type of items print(type(items))
Cách chuyển DataFrame bằng cú pháp sau:
# import pandas import pandas as pd # We create a dictionary of Pandas Series items = {'Bob' : pd.Series(data = [245, 25, 55], index = ['bike', 'pants', 'watch']), 'Alice' : pd.Series(data = [40, 110, 500, 45], index = ['book', 'glasses', 'bike', 'pants'])} # We create a Pandas DataFrame by passing it a dictionary of Pandas Series shopping_carts = pd.DataFrame(items) # We display the DataFrame shopping_carts
Kết quả
- Bob và Alice là chỉ số cột, index sẽ là những chỉ số đại diện cho dòng, và data sẽ thành dữ liệu của DF. Các bạn cần chú ý các giá trị NaN(các giá trị không được cung cấp ở items phía trên). Và chúng ta sẽ phải xử lí nó ở phần sau
- Nếu index không tạo dictionary items, kết quả sẽ như thế nào?
# import pandas import pandas as pd # We create a dictionary of Pandas Series without indexes data = {'Bob' : pd.Series([245, 25, 55]), 'Alice' : pd.Series([40, 110, 500, 45])} # We create a DataFrame df = pd.DataFrame(data) # Display the DataFrame df
Kết quả
Lúc này các chỉ số index sẽ là số bắt đầu từ 0. Bob không có phẩn tử thứ 4 nên bạn thấy có 1 giá trị NaN cuối cột Bob.
Cú pháp lấy thông tin từ DF:
# import pandas import pandas as pd # We create a dictionary of Pandas Series items = {'Bob' : pd.Series(data = [245, 25, 55], index = ['bike', 'pants', 'watch']), 'Alice' : pd.Series(data = [40, 110, 500, 45], index = ['book', 'glasses', 'bike', 'pants'])} # We create a Pandas DataFrame by passing it a dictionary of Pandas Series shopping_carts = pd.DataFrame(items) # We print some information about shopping_carts print('\n shopping_carts has shape:', shopping_carts.shape) print('\n shopping_carts has dimension:', shopping_carts.ndim) print('\n shopping_carts has a total of:', shopping_carts.size, 'elements') print('\n The data in shopping_carts is:\n', shopping_carts.values) print('\n The row index in shopping_carts is:', shopping_carts.index) print('\n The column index in shopping_carts is:', shopping_carts.columns)
Kết quả
Ngoài ra còn có thể tạo DF bằng list.
# import pandas import pandas as pd # We create a dictionary of lists (arrays) data = {'Integers' : [1,2,3], 'Floats' : [4.5, 8.2, 9.6]} # We create a DataFrame df = pd.DataFrame(data) # We display the DataFrame df
Kết quả
Trong thực tế khi muốn edit một DF, bạn có thể dùng list sẽ đơn giản hơn.
Cách dùng dictionaries để tạo DF.
# import pandas import pandas as pd # We create a list of Python dictionaries items = [{'bikes': 20, 'pants': 30, 'watches': 35}, {'watches': 10, 'glasses': 50, 'bikes': 15, 'pants':5}] # We create a DataFrame store_items = pd.DataFrame(items) # We display the DataFrame store_items
Kết quả
Cách truy xuất các phần tử của DF
# import pandas import pandas as pd # We create a list of Python dictionaries items = [{'bikes': 20, 'pants': 30, 'watches': 35}, {'watches': 10, 'glasses': 50, 'bikes': 15, 'pants':5}] # We create a DataFrame and provide the row index store_items = pd.DataFrame(items, index = ['store 1', 'store 2']) # We display the DataFrame store_items
Kết quả
Dưới đây là 1 số lệnh để truy xuất các phần tử của DF:
# import pandas import pandas as pd # We create a list of Python dictionaries items = [{'bikes': 20, 'pants': 30, 'watches': 35}, {'watches': 10, 'glasses': 50, 'bikes': 15, 'pants':5}] # We create a DataFrame and provide the row index store_items = pd.DataFrame(items, index = ['store 1', 'store 2']) # We access rows, columns and elements using labels print('\n How many bikes are in each store:\n') print(store_items[['bikes']]) print('\n How many bikes and pants are in each store:\n') print(store_items[['bikes', 'pants']]) print('\n What items are in Store 1:\n') print(store_items.loc[['store 1']]) print('\n How many bikes are in Store 2:') print(store_items['bikes']['store 2'])
Kết quả
Chú ý với câu lệnh đầu tiên so với lệnh thứ 3. Điểm khác biệt của 2 câu lệnh này là gì? câu lệnh 1 dùng để truy xuất cột và câu lệnh 3 dùng để truy xuất hàng.
Cú pháp thêm một cột và cách dùng list.
# import pandas import pandas as pd # We create a list of Python dictionaries items = [{'bikes': 20, 'pants': 30, 'watches': 35}, {'watches': 10, 'glasses': 50, 'bikes': 15, 'pants':5}] # We create a DataFrame and provide the row index store_items = pd.DataFrame(items, index = ['store 1', 'store 2']) # We add a new column named shirts to our store_items DataFrame # indicating the number of shirts in stock at each store. # We will put 15 shirts in store 1 and 2 shirts in store 2 store_items['shirts'] = [15,2] # We display the modified DataFrame store_items
Kết quả
Để thêm 1 hàng cho DF, thì chúng ta tạo 1 DF mới lưu dữ liệu hàng chúng ta muốn thêm, sau đó add nó vào DF cũ.
# import pandas import pandas as pd # We create a dictionary from a list of Python dictionaries # that will number of items at the new store new_items = [{'bikes': 20, 'pants': 30, 'watches': 35, 'glasses': 4}] # We create new DataFrame with the new_items # and provide and index labeled store 3 new_store = pd.DataFrame(new_items, index = ['store 3']) # We display the items at the new store new_store
Kết quả
# import pandas import pandas as pd # We create a list of Python dictionaries items = [{'bikes': 20, 'pants': 30, 'watches': 35}, {'watches': 10, 'glasses': 50, 'bikes': 15, 'pants':5}] # We create a DataFrame and provide the row index store_items = pd.DataFrame(items, index = ['store 1', 'store 2']) # We append store 3 to our store_items DataFrame store_items = store_items.append(new_store,sort=False) # We display the modified DataFrame store_items
Kết quả
# import pandas import pandas as pd # We create a list of Python dictionaries items = [{'bikes': 20, 'pants': 30, 'watches': 35}, {'watches': 10, 'glasses': 50, 'bikes': 15, 'pants':5}] # We create a DataFrame and provide the row index store_items = pd.DataFrame(items, index = ['store 1', 'store 2']) # We append store 3 to our store_items DataFrame store_items = store_items.append(new_store,sort=False) # We insert a new column with label shoes right before the column with numerical index 4 store_items.insert(4, 'shoes', [8,5,0]) # we display the modified DataFrame store_items
Kết quả
Có 1 điều lưu ý khi bạn hợp 2 DF lại với nhau thì thứ tự cột xếp theo thứ tự bảng chữ cái.
Chúng ta cũng có thể thêm 1 cột với cú pháp sau:
Cú pháp dataframe.insert(loc,label,data) được sử dụng, trong đó loc là vị trí(các bạn có thể thấy cột mới được chèn ở vị trí số 4), lable là tên cột, và cuối cùng là data để chèn vào.
Muốn xóa phần tử trong DF. Bạn có thể dùng .pop() hoặc .drop() để làm việc đó. Nhưng khác biệt là .pop() dùng để delete cột, còn drop thì cả cột và hàng bằng cách thay đổi chỉ số axis(số 1 là cột, số 0 là hàng).
# import pandas import pandas as pd # We create a list of Python dictionaries items = [{'bikes': 20, 'pants': 30, 'watches': 35}, {'watches': 10, 'glasses': 50, 'bikes': 15, 'pants':5}] # We create a DataFrame and provide the row index store_items = pd.DataFrame(items, index = ['store 1', 'store 2']) # We append store 3 to our store_items DataFrame store_items = store_items.append(new_store,sort=False) # We insert a new column with label shoes right before the column with numerical index 4 store_items.insert(4, 'shoes', [8,5,0]) # We remove the watches and shoes columns store_items = store_items.drop(['watches', 'shoes'], axis = 1) # we display the modified DataFrame store_items
Kết quả
# import pandas import pandas as pd # We create a list of Python dictionaries items = [{'bikes': 20, 'pants': 30, 'watches': 35}, {'watches': 10, 'glasses': 50, 'bikes': 15, 'pants':5}] # We create a DataFrame and provide the row index store_items = pd.DataFrame(items, index = ['store 1', 'store 2']) # We append store 3 to our store_items DataFrame store_items = store_items.append(new_store,sort=False) # We remove the store 2 and store 1 rows store_items = store_items.drop(['store 2', 'store 1'], axis = 0) # we display the modified DataFrame store_items
Kết quả
Xử lý giá trị NaN
# import pandas import pandas as pd # We create a list of Python dictionaries items = [{'bikes': 20, 'pants': 30, 'watches': 35, 'shirts': 15, 'shoes':8, 'suits':45}, {'watches': 10, 'glasses': 50, 'bikes': 15, 'pants':5, 'shirts': 2, 'shoes':5, 'suits':7}, {'bikes': 20, 'pants': 30, 'watches': 35, 'glasses': 4, 'shoes':10}] # We create a DataFrame and provide the row index store_items = pd.DataFrame(items, index = ['store 1', 'store 2', 'store 3']) # We display the DataFrame store_items
Kết quả
# import pandas import pandas as pd # We create a list of Python dictionaries items = [{'bikes': 20, 'pants': 30, 'watches': 35, 'shirts': 15, 'shoes':8, 'suits':45}, {'watches': 10, 'glasses': 50, 'bikes': 15, 'pants':5, 'shirts': 2, 'shoes':5, 'suits':7}, {'bikes': 20, 'pants': 30, 'watches': 35, 'glasses': 4, 'shoes':10}] # We create a DataFrame and provide the row index store_items = pd.DataFrame(items, index = ['store 1', 'store 2', 'store 3']) # giá trị NaN desc = store_items.isnull().sum() print(desc)
Kết quả
Nếu bạn muốn biết tổng số lượng phần tử có giá trị NaN:
# import pandas import pandas as pd # We create a list of Python dictionaries items = [{'bikes': 20, 'pants': 30, 'watches': 35, 'shirts': 15, 'shoes':8, 'suits':45}, {'watches': 10, 'glasses': 50, 'bikes': 15, 'pants':5, 'shirts': 2, 'shoes':5, 'suits':7}, {'bikes': 20, 'pants': 30, 'watches': 35, 'glasses': 4, 'shoes':10}] # We create a DataFrame and provide the row index store_items = pd.DataFrame(items, index = ['store 1', 'store 2', 'store 3']) num = store_items.isnull().sum().sum() print(num)
Kết quả
Tại sao phải xử lý NaN?, bảng chất NaN không có ý nghĩa gì khi đưa các thuật toán để trainning. Có thể áp dụng phương thức như .dropna(axis=0/1),
nhưng phương thức này có nhược điểm là xóa luôn cả dòng hoặc cột chứ NaN, dữ liệu sẽ bị mất. Vậy có phương pháp nào khác? Các bạn xem các dòng code phía dưới:
# import pandas import pandas as pd # We create a list of Python dictionaries items = [{'bikes': 20, 'pants': 30, 'watches': 35, 'shirts': 15, 'shoes':8, 'suits':45}, {'watches': 10, 'glasses': 50, 'bikes': 15, 'pants':5, 'shirts': 2, 'shoes':5, 'suits':7}, {'bikes': 20, 'pants': 30, 'watches': 35, 'glasses': 4, 'shoes':10}] # We create a DataFrame and provide the row index store_items = pd.DataFrame(items, index = ['store 1', 'store 2', 'store 3']) # We replace all NaN values with 0 store_items = store_items.fillna(0) store_items
Kết quả
Cách load dữ liệu từ file vào DF
Thông thường các bạn sẽ thấy dữ liệu lưu ở file csv. file
này đọc bằng excel và một số phần mềm khác được, mà thường là mình dùng excel.
Bây giờ mình sẽ sử dụng 1 file csv lưu dữ liệu cổ phiếu của Yahoo cung cấp theo link sau https://finance.yahoo.com/quote/GOOG/history/
Các bạn đưa file csv vào cùng file vào cùng folder chứa code. Còn nếu khác folder thì thay đường dẫn.
import pandas as pd # We load Google stock data in a DataFrame Google_stock = pd.read_csv('GOOG.csv') # We print some information about Google_stock print('Google_stock is of type:', type(Google_stock)) print('Google_stock has shape:', Google_stock.shape) Google_stock
Kết quả
Thông thường thì dữ liệu rất dài. chúng ta muốn xem 1 số đại diện coi nó ra sao thôi thì có 2 lệnh .head(N) và .tail(N) để mà show số dòng N đầu tiên hoặc cuối cùng(mặc định N = 5)
import pandas as pd # We load Google stock data in a DataFrame Google_stock = pd.read_csv('GOOG.csv') Google_stock.head()
Kết quả