Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

การเลือกข้อมูลย่อย (Subset) แบบ SQL Query Style ใน Pandas

การกรองข้อมูลใน Pandas แบบ SQL Style

Data Scientist มักต้องทำงานกับข้อมูลในฐานข้อมูลที่ต้องใช้ SQL ดึงข้อมูล Pandas มีวิธีการกรองข้อมูลที่คล้าย SQL 2 วิธีหลัก

สถานการณ์ตัวอย่าง

หาภาพยนตร์ที่: ภาษาเป็น en หรือ es, ความนิยม 500-1000, สถานะ Released, โหวต > 5000

SQL Equivalent

SELECT title, original_language, popularity, status, vote_count
FROM movies_data
WHERE original_language IN ('en', 'es')
  AND status = 'Released'
  AND popularity BETWEEN 500 AND 1000
  AND vote_count > 5000;

วิธี 1: Boolean Indexing

import pandas as pd
movies = pd.read_csv("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_lang & cond_status & cond_pop & cond_vote
cols = ["title", "original_language", "status", "popularity", "vote_count"]
result = movies.loc[final, cols]

วิธี 2: query() Method (SQL-like)

# ใช้สตริงเงื่อนไขแบบ SQL WHERE clause
conditions = (
    "original_language in ['en','es'] "
    "and status == 'Released' "
    "and popularity > 500 "
    "and popularity < 1000 "
    "and vote_count > 5000"
)
result = movies.query(conditions)

การใช้ตัวแปร Python ใน query()

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

ข้อดีของ query(): เร็วกว่า Boolean Indexing สำหรับ DataFrame ใหญ่, อ่านง่ายคล้าย SQL, รองรับตัวแปร Python ด้วย @