ভূমিকা
ডেটা সায়েন্সে প্রায়ই SQL ডাটাবেজ থেকে ডেটা আনতে হয়। Pandas-এ SQL-এর WHERE ক্লজের মত করে ডেটা ফিল্টার করার দুটি প্রধান পদ্ধতি আছে: Boolean Indexing এবং .query() মেথড।
দৃশ্যাঙ্ক (Scenario)
মুভি ডেটাসেট থেকে এমন মুভি বের করতে হবে যেখানে:
- ভাষা English (
en) বা Spanish (es) - জনপ্রিয়তা (popularity) ৫০০ থেকে ১০০০ এর মাঝে
- স্ট্যাটাস 'Released'
- ভোট কাউন্ট ৫০০০ এর বেশি
SQL কোয়ারি:
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;
পদ্ধতি ১: 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 = cond_lang & cond_status & cond_pop & cond_vote
cols = ["title", "original_language", "status", "popularity", "vote_count"]
movies.loc[final_cond, cols]
ফলাফল: Interstellar, Deadpool (২টি মুভি মেলে)
পদ্ধতি ২: .query() মেথড (SQL-লাইক সিনট্যাক্স)
final_cond = (
"original_language in ['en','es']"
" and status == 'Released'"
" and popularity > 500"
" and popularity < 1000"
" and vote_count > 5000"
)
movies.query(final_cond)
পাইথন ভেরিয়েবল ব্যবহার (অ্যাট @ সিম্বল):
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)
নোট: .query() বড় ডেটাফ্রেমে বুলিয়ান ইন্ডেক্সিং থেকে দ্রুত হয়ে থাকে। কলামের নামে স্পেস থাকলে আন্ডারস্কোর (_) দিয়ে রিপ্লেস করুন।