Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Bài 8: Cơ bản về Pandas

Pandas là thư viện chính cho việc thao tác và phân tích dữ liệu trong Python. Nó rất quan trọng để làm việc với dữ liệu không gian địa lý dạng bảng.

8.1. Mục tiêu học tập

import pandas as pd

8.2. Giới thiệu về Pandas

Pandas cung cấp DataFrame cho việc phân tích dữ liệu mạnh mẽ.

8.2.1. Tạo DataFrame từ dictionary

# Tạo DataFrame từ một dictionary
data = {
    'City': ['Hà Nội', 'TP.HCM', 'Đà Nẵng'],
    'Population': [8053663, 9420000, 1134000],
    'Latitude': [21.0285, 10.8231, 16.0544],
    'Longitude': [105.8542, 106.6297, 108.2022]
}
df = pd.DataFrame(data)
df.head()
CityPopulationLatitudeLongitude
0Hà Nội805366321.0285105.8542
1TP.HCM942000010.8231106.6297
2Đà Nẵng113400016.0544108.2022

8.2.2. Tạo DataFrame từ danh sách của từ điển (list of dictionary) hoặc danh sách lồng (list of lists)

# Từ một list các dictionaries
cities = [
    {'City': 'Hải Phòng', 'Population': 2028220, 'Latitude': 20.8449, 'Longitude': 106.6881},
    {'City': 'Cần Thơ', 'Population': 1235000, 'Latitude': 10.0452, 'Longitude': 105.7469}
]
df = pd.DataFrame(cities)
df.head()
CityPopulationLatitudeLongitude
0Hải Phòng202822020.8449106.6881
1Cần Thơ123500010.0452105.7469
# Tạo DataFrame từ list các lists với chỉ mục và tên cột tùy chỉnh
data = [
    ['Hà Nội', 8053663, 21.0285, 105.8542],
    ['TP.HCM', 9420000, 10.8231, 106.6297],
    ['Đà Nẵng', 1134000, 16.0544, 108.2022]
]
df = pd.DataFrame(data, columns=['City', 'Population', 'Latitude', 'Longitude']) # Thêm cột tương ứng
df.head()
CityPopulationLatitudeLongitude
0Hà Nội805366321.0285105.8542
1TP.HCM942000010.8231106.6297
2Đà Nẵng113400016.0544108.2022

8.3. Đọc và ghi CSV hoặc excel Files

CSV và excel là định dạng phổ biến nhất cho dữ liệu dạng bảng.

8.3.1. Đọc và ghi ra file csv

# Ghi DataFrame ra CSV
df.to_csv(r'G:\My Drive\python\geocourse\data\outputs\cities.csv', index=False)
# Đọc DataFrame từ CSV
df_read = pd.read_csv(r'G:\My Drive\python\geocourse\data\outputs\cities.csv')
df_read.head()  
CityPopulationLatitudeLongitude
0Hà Nội805366321.0285105.8542
1TP.HCM942000010.8231106.6297
2Đà Nẵng113400016.0544108.2022

8.3.2. Đọc và ghi ra file excel

# Đọc DataFrame từ Excel
df_excel = pd.read_excel(r'G:\My Drive\python\geocourse\data\outputs\cities.xlsx')  # Giả sử bạn có file cities.xlsx
# Ghi DataFrame ra Excel
df.to_excel(r'G:\My Drive\python\geocourse\data\outputs\cities_output.xlsx', index=False)

8.3.3. Đọc dữ liệu từ url

# Đọc dữ liệu từ URL
url = 'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv'
df = pd.read_csv(url)
# Lưu DataFrame ra file CSV
df.to_csv(r'G:\My Drive\python\geocourse\data\outputs\iris_data.csv', index=False)
# Lưu DataFrame ra file Excel
df.to_excel(r'G:\My Drive\python\geocourse\data\outputs\iris_data.xlsx', index=False)

8.4. Lọc và sắp xếp

Bạn có thể lọc các hàng và sắp xếp dữ liệu một cách dễ dàng.

8.4.1. Lọc và nhóm

# Dữ liệu Olympiad toán 2018 từ github bên dưới
df = pd.read_csv('https://raw.githubusercontent.com/leomtz/apmowebsite/refs/heads/master/data/data_clean/scoretable-2018-clean.csv')
df.head()
codecountryranklastfirstsexp1p2p3p4p5total
0ARGArgentina1MASLIAHJULIÁNM7615019
1ARGArgentina2FLESCHLERIANM7704018
2ARGArgentina3SOTOCARLOS MIGUELM7045016
3ARGArgentina4DI SANZOBRUNOM7305015
4ARGArgentina5CASSIANICOLÁSM7312013
# Lọc những thí sinh có rank dưới 3
ranked_df = df[df['rank'] < 3]
# Sắp xếp theo điểm tổng (Total Score) giảm dần
sorted_df = df.sort_values(by='total', ascending=False)
sorted_df.head()
codecountryranklastfirstsexp1p2p3p4p5total
342USAUnited States of America1GuAndrewM7777735
343USAUnited States of America2WanEdwardM7777735
146KORRepublic of Korea2KimJi MinM7777735
147KORRepublic of Korea3KimDainF7777735
145KORRepublic of Korea1KwonSunghyunM7777735
# Tóm tắt điểm trung bình theo quốc gia
mean_scores = df.groupby('country')['total'].mean().reset_index().sort_values(by='total', ascending=False)
mean_scores.head()
countrytotal
27Republic of Korea32.0
38United States of America30.6
15Japan25.4
30Singapore23.1
6Canada22.0

8.4.2. Tạo cột mới và gộp các DataFrames

# Tạo ra cột mới fullname bằng cách ghép first_name và last_name
df['fullname'] = df['first'] + ' ' + df['last']
df.head()
codecountryranklastfirstsexp1p2p3p4p5totalfullname
0ARGArgentina1MASLIAHJULIÁNM7615019JULIÁN MASLIAH
1ARGArgentina2FLESCHLERIANM7704018IAN FLESCHLER
2ARGArgentina3SOTOCARLOS MIGUELM7045016CARLOS MIGUEL SOTO
3ARGArgentina4DI SANZOBRUNOM7305015BRUNO DI SANZO
4ARGArgentina5CASSIANICOLÁSM7312013NICOLÁS CASSIA
# Gộp 2 dataframes theo cột chung 'id'
df1 = pd.DataFrame({
    'id': [1, 2, 3],
    'value1': ['A', 'B', 'C']
})
df2 = pd.DataFrame({
    'id': [2, 3, 4],
    'value2': ['D', 'E', 'F']
})
merged_df = pd.merge(df1, df2, on='id', how='inner') # Thay 'inner' bằng 'outer', 'left', hoặc 'right' để thay đổi kiểu gộp
merged_df.head()
idvalue1value2
02BD
13CE

8.5. Tóm tắt dữ liệu

Pandas giúp dễ dàng lấy thống kê và tóm tắt.

# tóm tắt dữ liệu df 
summary = df.describe()
# Tóm tắt chỉ cột số liệu
numeric_summary = df.describe(include=['number'])
# Tóm tắt chỉ cột đối tượng
categorical_summary = df.describe(include=['object'])
C:\Users\tuyen\AppData\Local\Temp\ipykernel_12788\2741901675.py:6: Pandas4Warning: For backward compatibility, 'str' dtypes are included by select_dtypes when 'object' dtype is specified. This behavior is deprecated and will be removed in a future version. Explicitly pass 'str' to `include` to select them, or to `exclude` to remove them and silence this warning.
See https://pandas.pydata.org/docs/user_guide/migration-3-strings.html#string-migration-select-dtypes for details on how to write code that works with pandas 2 and 3.
  categorical_summary = df.describe(include=['object'])
# Tóm tắt dữ liệu nhiều thông số 
stats = df.groupby('country').agg({
    'total': ['mean', 'max', 'min'],
    'rank': ['mean', 'max', 'min']
})
stats = stats.reset_index()
stats.head()
totalrank
meanmaxminmeanmaxmin
country
Argentina12.21975.5101
Australia16.521125.5101
Bangladesh13.52195.5101
Bolivia13.22133.051
Brazil14.820125.5101

Tóm tắt

Bạn đã hoàn thành Bài 8 và học được Pandas - thư viện quan trọng nhất cho data analysis trong Python.

Các khái niệm chính đã nắm vững:

Kỹ năng bạn có thể áp dụng: