Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Cách chọn tập con dữ liệu theo phong cách SQL trong Pandas (Python)

Giới thiệu

Data Scientist thường phải làm việc với dữ liệu từ database (SQL). Thư viện Pandas của Python cung cấp hai cách chính để lọc dữ liệu kiểu SQL: Boolean Indexing và phương thức .query().

Senario: Lọc phim

  • Ngôn ngữ: English (en) hoặc Spanish (es)
  • Độ phổ biến: 500 - 1000
  • Trạng thái: Released
  • Số lượt vote > 5000

Phương pháp 1: Boolean Indexing

import pandas as pd
movies = pd.read_csv("https://raw.githubusercontent.com/sasankac/TestDataSet/master/movies_data.csv")

languages = ["en", "es"]
cond_lang = movies.original_language.isin(languages)
cond_status = movies.status == "Released"
cond_pop = movies.popularity.between(500, 1000)
cond_vote = movies.vote_count > 5000

final_cond = cond_lang & cond_status & cond_pop & cond_vote
cols = ["title", "original_language", "status", "popularity", "vote_count"]
movies.loc[final_cond, cols]

Kết quả (2 phim): Interstellar, Deadpool

Phương pháp 2: .query() (kiểu SQL WHERE)

final_cond = (
    "original_language in ['en','es']"
    " and status == 'Released'"
    " and popularity > 500"
    " and popularity < 1000"
    " and vote_count > 5000"
)
movies.query(final_cond)

Tối ưu với biến Python (@):

movie_languages = ['en', 'es']
final_cond = (
    "original_language in @movie_languages"
    " and status == 'Released'"
    " and popularity > 500"
    " and popularity < 1000"
    " and vote_count > 5000"
)
movies.query(final_cond)

Lưu ý: .query() thường nhanh hơn trên DataFrame lớn. Tên cột không được chứa khoảng trắng (thay bằng underscore). Không dùng chuỗi triple-quoted đa dòng trong .query().