Skip to main content

Setting Up and Loading Data

Getting started guide with Exploratory Data Analysis (EDA)​

Exploratory Data Analysis (EDA) is the most critical step before building any Machine Learning model. This document will guide you through setting up your environment and the first steps of working with data using the Pandas library.

1/ Installing Necessary Libraries for EDA​

To complete the entire data analysis process, you need to install a basic Python library ecosystem. You can open your Terminal (or Command Prompt / Anaconda Prompt) and run the following commands:

Using pip (Python Default):​

pip install pandas numpy matplotlib seaborn scikit-learn jupyter

Using conda (If using Anaconda/Miniconda):​

conda install pandas numpy matplotlib seaborn scikit-learn jupyter

Library Overview:

  • pandas: The core library for manipulating, cleaning, and processing tabular data.
  • numpy: A high-performance library for numerical computing and matrix operations.
  • matplotlib & seaborn: Two libraries used for charting and Data Visualization.
  • scikit-learn: A library providing Machine Learning algorithms and data preprocessing tools (such as scaling, encoding).
  • jupyter: An interactive coding environment (Jupyter Notebook) ideally suited for data analysis.

2/ Part 1: Importing data into Pandas (Data Import)​

In Pandas, the primary object used to store tabular data is called a DataFrame. Here are the fundamental ways to create and import data.

2.1. Creating and Displaying Data from In-Memory/Hardcoded Data​

If you have a small amount of data, you can instantiate a DataFrame directly from a Python Dictionary or List.

import pandas as pd

# 1. Define sample data (Dictionary)
data = {
'Student ID': ['SV001', 'SV002', 'SV003', 'SV004', 'SV005'],
'Full Name': ['Nguyen Van A', 'Tran Thi B', 'Le Van C', 'Pham Thi D', 'Hoang Van E'],
'Math Score': [8.5, 9.0, 7.5, 6.0, 9.5],
'Physics Score': [7.0, 8.5, 8.0, 6.5, 9.0],
'Scholarship': [False, True, False, False, True]
}

# 2. Convert data into a Pandas DataFrame
df = pd.DataFrame(data)

# 3. Print the entire dataset
print("COMPLETE DATA TABLE")
display(df) # Use display() in Jupyter Notebook for formatted rendering, or use print(df) in a standard script.

# 4. Preview the first 3 rows
print("\nFIRST 3 ROWS")
display(df.head(3))

2.2. Generalized Function to Load Data from Local Disk​

In production and practical workflows, data is typically loaded from files stored on disk (CSV, Excel) rather than manual entry. Here is a utility function to automate reading files based on their extension.

import pandas as pd
import os

def load_data_from_file(filepath):
"""
Reads data from a local file.
Automatically detects the format based on file extension.
"""
# Verify file existence
if not os.path.exists(filepath):
print(f"Error: File not found at path '{filepath}'")
return None

# Extract file extension (e.g., .csv, .xlsx)
_, file_extension = os.path.splitext(filepath)
file_extension = file_extension.lower()

try:
if file_extension == '.csv':
df = pd.read_csv(filepath)
elif file_extension in ['.xls', '.xlsx']:
df = pd.read_excel(filepath)
elif file_extension == '.json':
df = pd.read_json(filepath)
elif file_extension == '.parquet':
df = pd.read_parquet(filepath)
else:
print(f"Error: Unsupported format {file_extension} in this function.")
return None

print(f"Data loaded successfully! Shape (Rows, Columns): {df.shape}")
return df

except Exception as e:
print(f"An error occurred while reading the file: {e}")
return None

# Usage examples:
# df_sales = load_data_from_file('C:/Users/Data/sales_2026.csv')
# df_customers = load_data_from_file('/Users/hungdan/Documents/customers.xlsx')

2.3. Detailed Data Formats Supported by Pandas (I/O)​

Pandas provides extensive I/O capabilities, supporting most industry-standard data formats out of the box:

File Format / SourceRead FunctionWrite / Save FunctionDescription
CSV (Comma-Separated Values)read_csv()to_csv()The most ubiquitous text-based tabular format, delimited by commas or semicolons. Lightweight and universally compatible.
Excelread_excel()to_excel()Reads/writes Microsoft Excel spreadsheets (.xls, .xlsx). Requires auxiliary engines such as openpyxl (for xlsx) or xlrd (for xls).
JSON (JavaScript Object Notation)read_json()to_json()Hierarchical key-value structure, standard for Web API integrations and document storage.
SQL (Databases)read_sql() read_sql_table() read_sql_query()to_sql()Direct connectivity to relational databases (MySQL, PostgreSQL, SQLite, SQL Server) via SQL queries. Requires SQLAlchemy.
HTMLread_html()to_html()Automated web-scraping utility. Scans web pages or URLs for <table> tags and parses them into a list of DataFrames.
Parquetread_parquet()to_parquet()High-performance columnar storage format optimized for Big Data workflows. Significantly smaller file footprint and faster disk I/O compared to CSV. Requires pyarrow or fastparquet.
Pickleread_pickle()to_pickle()Native Python object serialization. Preserves exact DataFrame structure and data types at high speed; exclusive to Python ecosystems.
Featherread_feather()to_feather()Ultra-fast, lightweight binary format designed for interoperability between Python and R.
HDF5read_hdf()to_hdf()High-performance format suited for large-scale scientific datasets (multi-gigabyte range) with native compression.
SAS / SPSS / Stataread_sas() read_spss() read_stata()to_stata()Proprietary binary formats generated by statistical computing suites common in academic and financial research.
XMLread_xml()to_xml()Extensible Markup Language; parses structured hierarchical documents via tag configurations similar to HTML.

Note: Our materials may contain mistakes or oversights. If you notice any errors, please feel free to leave your feedback. Thank you so much for your support!

VIET VERSION​

Hướng dẫn EDA​

Exploratory Data Analysis - EDA là bước quan trọng nhất trước khi xây dựng bất kỳ mô hình Machine Learning nào. Tài liệu này sẽ hướng dẫn các bạn cách cài đặt công cụ và những bước đầu tiên để làm việc với dữ liệu bằng thư viện Pandas.

1/ Cài đặt các thư viện cần thiết cho EDA​

Để thực hiện trọn vẹn quá trình phân tích dữ liệu, các bạn cần cài đặt các thư viện cơ bản của Python. Bạn có thể mở Terminal (hoặc Command Prompt / Anaconda Prompt) và chạy các lệnh sau:

Sử dụng pip (Mặc định của Python):​

pip install pandas numpy matplotlib seaborn scikit-learn jupyter

Sử dụng conda (Nếu bạn dùng Anaconda/Miniconda):​

conda install pandas numpy matplotlib seaborn scikit-learn jupyter

Giải thích các thư viện:

  • pandas: Thư viện cốt lõi để thao tác, làm sạch và xử lý dữ liệu dạng bảng.
  • numpy: Thư viện tính toán toán học và ma trận tốc độ cao.
  • matplotlib & seaborn: Hai thư viện dùng để vẽ biểu đồ và trực quan hóa dữ liệu (Data Visualization).
  • scikit-learn: Thư viện cung cấp các thuật toán Machine Learning và các công cụ tiền xử lý dữ liệu (như chuẩn hóa, mã hóa).
  • jupyter: Môi trường viết code tương tác (Jupyter Notebook) cực kỳ phù hợp cho việc phân tích dữ liệu.

2/ Phần 1: Nhập dữ liệu vào Pandas (Data Import)​

Trong Pandas, đối tượng chính để chứa dữ liệu bảng được gọi là DataFrame. Các cách cơ bản để tạo và nhập dữ liệu:

2.1. Tạo và in bảng dữ liệu từ dữ liệu cho sẵn (Hardcoded Data)​

Nếu các bạn đã có sẵn một lượng nhỏ dữ liệu, các bạn có thể tạo DataFrame trực tiếp từ Dictionary hoặc List của Python.

import pandas as pd

# 1. Khai báo dữ liệu có sẵn (Dictionary)
data = {
'Mã SV': ['SV001', 'SV002', 'SV003', 'SV004', 'SV005'],
'Họ và Tên': ['Nguyễn Văn A', 'Trần Thị B', 'Lê Văn C', 'Phạm Thị D', 'Hoàng Văn E'],
'Điểm Toán': [8.5, 9.0, 7.5, 6.0, 9.5],
'Điểm Lý': [7.0, 8.5, 8.0, 6.5, 9.0],
'Đạt Học Bổng': [False, True, False, False, True]
}

# 2. Chuyển đổi dữ liệu thành Pandas DataFrame
df = pd.DataFrame(data)

# 3. In toàn bộ bảng dữ liệu
print("TOÀN BỘ BẢNG DỮ LIỆU")
display(df) # Dùng display() trong Jupyter Notebook để hiển thị bảng đẹp hơn, hoặc dùng print(df) trong script thường.

# 4. In 3 dòng đầu tiên của bảng
print("\n3 DÒNG ĐẦU TIÊN")
display(df.head(3))

2.2. Hàm tổng quát để đọc dữ liệu từ máy tính​

Trong thực tế, các bạn sẽ hiếm khi tự gõ dữ liệu mà sẽ đọc từ các file (CSV, Excel) được lưu về. Có một hàm Python khá tiện giúp các bạn đọc dữ liệu tự động dựa trên đuôi file:

import pandas as pd
import os

def load_data_from_file(filepath):
"""
Hàm đọc dữ liệu từ file máy tính.
Tự động nhận diện định dạng dựa trên đuôi file (extension).
"""
# Kiểm tra xem file có tồn tại không
if not os.path.exists(filepath):
print(f"Lỗi: Không tìm thấy file tại đường dẫn '{filepath}'")
return None

# Lấy đuôi file (ví dụ: .csv, .xlsx)
_, file_extension = os.path.splitext(filepath)
file_extension = file_extension.lower()

try:
if file_extension == '.csv':
df = pd.read_csv(filepath)
elif file_extension in ['.xls', '.xlsx']:
df = pd.read_excel(filepath)
elif file_extension == '.json':
df = pd.read_json(filepath)
elif file_extension == '.parquet':
df = pd.read_parquet(filepath)
else:
print(f"Lỗi: Chưa hỗ trợ đọc định dạng {file_extension} trong hàm này.")
return None

print(f"Đọc dữ liệu thành công! Kích thước dữ liệu (Dòng, Cột): {df.shape}")
return df

except Exception as e:
print(f"Đã xảy ra lỗi khi đọc file: {e}")
return None

# Cách sử dụng:
# df_sales = load_data_from_file('C:/Users/Data/sales_2026.csv')
# df_customers = load_data_from_file('/Users/hungdan/Documents/customers.xlsx')

2.3. Chi tiết các định dạng dữ liệu mà Pandas có thể đọc/ghi​

Pandas là một công cụ cực kỳ mạnh mẽ nhờ khả năng hỗ trợ (I/O) hầu hết các định dạng dữ liệu phổ biến trên thế giới.

Định dạng File / NguồnHàm Đọc (Read)Hàm Ghi (Write / Save)Mô tả chi tiết
CSV (Comma-Separated Values)read_csv()to_csv()Định dạng văn bản phổ biến nhất, dùng dấu phẩy (hoặc dấu chấm phẩy) để ngăn cách các cột. Rất nhẹ và mở được bằng mọi phần mềm.
Excelread_excel()to_excel()Đọc/ghi các file của Microsoft Excel (.xls, .xlsx). Yêu cầu cài thêm thư viện phụ trợ như openpyxl (cho xlsx) hoặc xlrd (cho xls).
JSON (JavaScript Object Notation)read_json()to_json()Định dạng cấu trúc dạng cây/từ điển, thường dùng phổ biến khi lấy dữ liệu từ các API trên Web.
SQL (Databases)read_sql()
read_sql_table()
read_sql_query()
to_sql()Kết nối trực tiếp vào cơ sở dữ liệu (MySQL, PostgreSQL, SQLite, SQL Server) thông qua câu lệnh truy vấn SQL. Cần thư viện SQLAlchemy.
HTMLread_html()to_html()Cực kỳ hữu ích để "cào" (scrape) dữ liệu. Hàm này tự động quét mã nguồn trang web và lấy ra tất cả các bảng (thẻ <table>) rồi biến thành list các DataFrames.
Parquetread_parquet()to_parquet()Định dạng lưu trữ dữ liệu dạng cột (Columnar format) cực kỳ tối ưu cho Big Data. File nhẹ hơn CSV rất nhiều và tốc độ đọc siêu nhanh. Yêu cầu thư viện pyarrow hoặc fastparquet.
Pickleread_pickle()to_pickle()Định dạng lưu trữ nhị phân riêng của Python. Dùng để lưu lại DataFrame nguyên trạng (giữ nguyên kiểu dữ liệu của từng cột) cực nhanh, nhưng không dùng được cho ngôn ngữ khác ngoài Python.
Featherread_feather()to_feather()Một định dạng nhị phân nhẹ và cực nhanh khác, tốt để luân chuyển dữ liệu giữa Python và ngôn ngữ R.
HDF5read_hdf()to_hdf()Dùng cho dữ liệu có kích thước cực lớn (hàng chục GB), hỗ trợ nén dữ liệu.
SAS / SPSS / Stataread_sas()
read_spss()
read_stata()
to_stata()Các định dạng đặc thù lấy từ các phần mềm thống kê chuyên dụng trong học thuật và tài chính.
XMLread_xml()to_xml()Định dạng ngôn ngữ đánh dấu mở rộng, cấu trúc có dạng thẻ (tags) tương tự HTML.

Lưu ý: Tài liệu của chúng mình có thể còn sai sót, rất mong nhận được góp ý của các bạn khi phát hiện sai sót. Mình xin chân thành cảm ơn các bạn!