ရိုးရိုးလေး ရှင်းပြမယ်
pandas ကို ရိုးရိုးလေး ပြောရရင်
pandas ဆိုတာ Python ထဲက spreadsheet တစ်ခုလိုပါပဲ။ DataFrame က နာမည်ပါတဲ့ column တွေနဲ့ label ပါတဲ့ row တွေ ပါဝင်တဲ့ ဇယားဖြစ်ပြီး Series ကတော့ အဲဒီ ဇယားထဲက column တစ်ခုတည်းပါ။ Column တစ်ခုစီရဲ့ အောက်မှာ NumPy လို array တစ်ခု ရှိလို့ column တစ်ခုလုံးကို တစ်ကြိမ်တည်း တွက်လို့ ရပါတယ်။
CSV, Excel, JSON, SQL database ကနေ data ကို ဖတ်ပြီး ရှင်းလင်း၊ စစ်ထုတ်၊ အုပ်စုခွဲပြီး summary ထုတ်တာက pandas ရဲ့ အဓိက အလုပ်ပါ။ 'မြို့တစ်မြို့ချင်းရဲ့ ရောင်းအား ဘယ်လောက်လဲ' လို မေးခွန်းကို loop မရေးဘဲ code တစ်ကြောင်း နှစ်ကြောင်းနဲ့ ဖြေနိုင်ပါတယ်။
Problem → Why → Solution
ပြဿနာ: dictionary list နဲ့ report ထုတ်ရတာ
Order တွေကို dictionary list အဖြစ် ရထားပြီး မြို့အလိုက် ဝင်ငွေ စုစုပေါင်းကို ထုတ်ရမယ် ဆိုပါစို့။ Revenue တွက်ဖို့ loop တစ်ခု၊ မြို့အလိုက် စုဖို့ dictionary တစ်ခု၊ စီဖို့ sorted() — code က တဖြည်းဖြည်း ရှည်လာပါတယ်။ Manager က 'quantity ၂ ကျော်တဲ့ order တွေပဲ' လို့ ထပ်တောင်းရင် loop တွေကို ပြန်ပြင်ရပြန်ပါတယ်။
orders = [
{"city": "Yangon", "qty": 3, "price": 2.5},
{"city": "Mandalay", "qty": 1, "price": 4.0},
{"city": "Yangon", "qty": 2, "price": 4.0},
]
totals = {}
for o in orders:
revenue = o["qty"] * o["price"]
totals[o["city"]] = totals.get(o["city"], 0) + revenue
report = sorted(totals.items(), key=lambda kv: kv[1], reverse=True)
print(report)pandas က ဘာကို ပိုကောင်းစေလဲ
pandas နဲ့ဆိုရင် revenue က column ၂ ခုကို မြှောက်တဲ့ expression တစ်ခု၊ filter က condition တစ်ခု၊ report က groupby တစ်ကြောင်းပဲ ဖြစ်ပါတယ်။ Logic က data shape ကို ဖော်ပြတဲ့ နေရာမှာ ရှိနေလို့ condition အသစ် ထပ်ထည့်ရတာ ပိုလွယ်ပြီး pandas က missing value, data type, sorting တွေကိုလည်း တသမတ်တည်း ကိုင်တွယ်ပေးပါတယ်။
Core concept: index, column, filter နဲ့ groupby
DataFrame မှာ အပိုင်း သုံးခု ရှိပါတယ်: column နာမည်တွေ၊ row label တွေ ဖြစ်တဲ့ index နဲ့ column တစ်ခုစီရဲ့ value array တွေပါ။ Index ကို ကိုယ်တိုင် မပေးရင် 0, 1, 2 ... RangeIndex ကို သုံးပါတယ်။ Column တစ်ခုစီမှာ dtype ကိုယ်ပိုင် ရှိပြီး df.dtypes က ပြပေးပါတယ်။ pandas 3 မှာ text column တွေက default အားဖြင့် str dtype ဖြစ်ပါတယ်၊ version အဟောင်းတွေမှာတော့ object လို့ ပြလေ့ရှိပါတယ်။
df["qty"] လို string တစ်ခုနဲ့ ရွေးရင် Series တစ်ခု ရပြီး df[["qty", "price"]] လို list နဲ့ ရွေးရင် DataFrame အသစ် ရပါတယ်။ Row နဲ့ column နှစ်ခုလုံးကို ရွေးချင်ရင် label အလိုက် ရွေးတဲ့ loc နဲ့ position အလိုက် ရွေးတဲ့ iloc ကို သုံးပါ။ df.loc[row_condition, "qty"] ဆိုတဲ့ ပုံစံက 'ဒီ condition ကိုက်တဲ့ row တွေရဲ့ qty column' လို့ ဖတ်ပါတယ်။ loc ရဲ့ label slice က အဆုံးကိုပါ ထည့်ပြီး iloc ကတော့ Python slice လို အဆုံးကို မထည့်ပါဘူး။
| ရေးနည်း | ဘာကို ရွေးလဲ |
|---|---|
| df["qty"] | Column တစ်ခု၊ Series အဖြစ် |
| df[mask] | mask မှာ True ဖြစ်တဲ့ row တွေ |
| df.loc[2, "qty"] | index label 2 ရဲ့ qty value |
| df.iloc[0:2, 1] | ပထမ row ၂ ခု၊ ဒုတိယ column |
Series နှစ်ခုကို ပေါင်းတာ၊ မြှောက်တာ လုပ်တဲ့အခါ pandas က position နဲ့ မဟုတ်ဘဲ index label နဲ့ တွဲပါတယ်။ Index မတူတဲ့ Series နှစ်ခုကို ပေါင်းရင် ကိုက်ညီတဲ့ label မရှိတဲ့ နေရာတွေမှာ NaN ထွက်လာလို့ ဒါကို alignment လို့ ခေါ်ပါတယ်။
Filter လုပ်တာက NumPy mask နဲ့ အတူတူပါပဲ: df["qty"] > 2 က row တစ်ခုကို True/False တစ်ခု ပါတဲ့ Series ပြန်ပေးပြီး df[mask] က True row တွေကိုပဲ ထားပါတယ်။ Condition နှစ်ခု ပေါင်းရင် and/or မဟုတ်ဘဲ & နဲ့ | ကို သုံးရပြီး condition တစ်ခုစီကို ကွင်းထဲ ထည့်ရပါတယ်၊ operator precedence ကြောင့်ပါ။
groupby က split-apply-combine ဆိုတဲ့ အဆင့် သုံးဆင့် ပုံစံနဲ့ အလုပ်လုပ်ပါတယ်: key column ရဲ့ value အလိုက် row တွေကို အုပ်စုခွဲ၊ အုပ်စုတစ်ခုစီမှာ sum, mean, count လို function ကို run၊ ပြီးရင် ရလဒ်တွေကို group key ကို index အဖြစ် ထားတဲ့ ဇယားအသစ်တစ်ခုထဲ ပြန်ပေါင်းပါတယ်။ agg(["count", "sum"]) ဒါမှမဟုတ် named aggregation, agg(total=("revenue", "sum")) နဲ့ summary အများကြီးကို တစ်ပြိုင်နက် ထုတ်လို့ ရပါတယ်။
- dtypes နဲ့ head() နဲ့ ကြည့်
- Column ကို expression နဲ့ ဆင့်ပွား
- Boolean mask နဲ့ row တွေ ရွေး
- groupby: ခွဲ၊ တွက်၊ ပြန်ပေါင်း
Row တစ်ခုချင်းကို loop ပတ်ချင်စိတ် ပေါ်လာတိုင်း column တစ်ခုလုံးပေါ်မှာ အလုပ်လုပ်တဲ့ နည်း ရှိမရှိ အရင် ရှာပါ။
အထွေထွေ ပုံစံ
import pandas as pd
df = pd.DataFrame({"col_a": [...], "col_b": [...]}) # or pd.read_csv(path)
df.shape, df.dtypes, df.head()
df["new_col"] = df["col_a"] * df["col_b"]
subset = df[(df["col_a"] > x) & (df["col_b"] == y)]
df.loc[row_mask, "col_b"] = new_value
summary = df.groupby("key")["value"].agg(["count", "sum"])
summary.sort_values("sum", ascending=False)Data ကို load လုပ်ပြီး ကြည့်ပါ၊ column အသစ်ကို expression နဲ့ ဆောက်ပါ၊ mask နဲ့ filter လုပ်ပါ၊ ပြင်ဖို့ loc ကို သုံးပါ၊ နောက်ဆုံး groupby နဲ့ summary ထုတ်ပါ။
Worked example: café order report
အောက်က program က မြို့ သုံးမြို့က café order ၆ ခုကို DataFrame အဖြစ် ဆောက်ပါတယ်။ Problem section က loop တွေကို revenue column, boolean filter, loc နဲ့ groupby report တို့နဲ့ အစားထိုးထားပြီး output ထဲက dtypes မှာ pandas 3 ရဲ့ str dtype ကို တွေ့ရပါမယ်။
import pandas as pd
orders = pd.DataFrame({
"order_id": [101, 102, 103, 104, 105, 106],
"city": ["Yangon", "Mandalay", "Yangon", "Bago", "Mandalay", "Yangon"],
"product": ["tea", "coffee", "coffee", "tea", "tea", "cake"],
"qty": [3, 1, 2, 5, 2, 4],
"price": [2.5, 4.0, 4.0, 2.5, 2.5, 3.0],
})
print(orders.shape)
print(orders.dtypes)
orders["revenue"] = orders["qty"] * orders["price"] # whole column at once
print(orders.head(3))
big = orders[orders["revenue"] >= 10] # boolean filter
print(big[["order_id", "city", "revenue"]])
print(orders.loc[orders["city"] == "Yangon", "qty"].sum())
by_city = (
orders.groupby("city")["revenue"]
.agg(["count", "sum"])
.sort_values("sum", ascending=False)
)
print(by_city)Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Inspect the table
print(orders.dtypes)Column တစ်ခုစီရဲ့ dtype ကို ပြပါတယ်: order_id နဲ့ qty က int64၊ price က float64၊ city နဲ့ product က str ပါ။ Number column တစ်ခုက str ဖြစ်နေရင် တွက်ချက်မှု မစခင် ပြင်ရပါမယ်။
- Derive a column
orders["revenue"] = orders["qty"] * orders["price"] # whole column at onceSeries နှစ်ခုကို index ချင်း တွဲပြီး မြှောက်ကာ column အသစ်အဖြစ် ထည့်ပါတယ်။ Loop မလိုဘဲ row ၆ ခုလုံးကို တစ်ပြိုင်နက် တွက်ပါတယ်။
- Filter rows
big = orders[orders["revenue"] >= 10] # boolean filterMask က row ၆ ခုအတွက် True/False ၆ ခုပါပြီး True ဖြစ်တဲ့ order 104 နဲ့ 106 ပဲ ကျန်ပါတယ်။ Index label 3 နဲ့ 5 ကို ဆက်ထိန်းထားတာကို output မှာ သတိထားကြည့်ပါ။
- loc with a condition
print(orders.loc[orders["city"] == "Yangon", "qty"].sum())loc[row condition, column] ပုံစံနဲ့ Yangon row တွေရဲ့ qty ကိုပဲ ရွေးပြီး ပေါင်းလို့ 3 + 2 + 4 = 9 ရပါတယ်။
- Group and sort
.agg(["count", "sum"])groupby("city") က row တွေကို မြို့အလိုက် ခွဲပြီး agg က revenue ပေါ်မှာ count နဲ့ sum ကို တွက်ပါတယ်။ ရလဒ်ရဲ့ index က city ဖြစ်ပြီး sort_values နဲ့ အများဆုံးကနေ စီပါတယ်။
(6, 5)
order_id int64
city str
product str
qty int64
price float64
dtype: object
order_id city product qty price revenue
0 101 Yangon tea 3 2.5 7.5
1 102 Mandalay coffee 1 4.0 4.0
2 103 Yangon coffee 2 4.0 8.0
order_id city revenue
3 104 Bago 12.5
5 106 Yangon 12.0
9
count sum
city
Yangon 3 27.5
Bago 1 12.5
Mandalay 2 9.0File တွေ ဖတ်ခြင်း၊ ရေးခြင်းနဲ့ data ကို စစ်ဆေးခြင်း
လက်တွေ့မှာ DataFrame ကို dictionary ကနေ ဆောက်တာထက် file ကနေ ဖတ်တာ ပိုများပါတယ်။ pd.read_csv, pd.read_json, pd.read_sql နဲ့ pd.read_excel (openpyxl လို engine တစ်ခု ထပ်သွင်းဖို့ လိုပါတယ်) တို့က DataFrame ကို ပြန်ပေးပြီး to_csv(path, index=False) က index column မပါဘဲ ပြန်ရေးပါတယ်။
import io
import pandas as pd
csv_text = "city,qty\nYangon,3\nBago,\nMandalay,2\n"
df = pd.read_csv(io.StringIO(csv_text)) # same call works with a file path
df.info() # prints a summary itself and returns None
print(df.isna().sum()) # missing values per column
print(df.describe()) # count, mean, std, min, quartiles, maxinfo() ကို print() ထဲ မထည့်ပါနဲ့
df.info() က summary ကို ကိုယ်တိုင် print ထုတ်ပြီး None ကို return ပြန်ပါတယ်။ print(df.info()) လို့ ရေးရင် summary ရဲ့ နောက်မှာ None ဆိုတဲ့ စာလုံး ထပ်ပေါ်လာပါတယ်။ Missing value ရှိလို့ qty column က float64 ဖြစ်သွားတာကိုလည်း info() မှာ တွေ့ရပါမယ်။
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ pandas
Data analyst, backend developer နဲ့ ML engineer တွေ အားလုံးနီးပါး pandas ကို နေ့စဉ် သုံးကြပါတယ်။ အများအားဖြင့် ပုံစံက တူပါတယ်: source တစ်ခုကနေ ဖတ်၊ dtype နဲ့ missing value ကို ရှင်း၊ column အသစ် ဆင့်ပွား၊ filter နဲ့ group လုပ်ပြီး report ဒါမှမဟုတ် model input အဖြစ် ထုတ်ပါတယ်။ Memory ထက် ကြီးတဲ့ file တွေအတွက်တော့ DataFrame အကြီးကြီး တစ်ခုတည်း မဆောက်ဘဲ chunk လိုက် ဖတ်တာ ဒါမှမဟုတ် database ကို သုံးတာမျိုး ပြောင်းလုပ်ကြပါတယ်။
- Business report: database ကနေ ရောင်းအား data ကို read_sql နဲ့ ဆွဲထုတ်ပြီး groupby(["region", "month"]) နဲ့ လစဉ် summary လုပ်ကာ Excel ဒါမှမဟုတ် CSV အဖြစ် အပတ်စဉ် ပို့ပါတယ်။
- Data cleaning pipeline: drop_duplicates, fillna, astype နဲ့ str.strip တို့ကို function တစ်ခုထဲ စုထားပြီး raw file အသစ် ရောက်တိုင်း တူညီတဲ့ အဆင့်တွေကို run ပါတယ်။
- Machine learning: CSV ကနေ feature column တွေကို ရွေး၊ category တွေကို pd.get_dummies နဲ့ ပြောင်းပြီး df.to_numpy() နဲ့ model ဆီ ပေးပါတယ်။
အမှားများ
pandas နဲ့ ဖြစ်လေ့ရှိတဲ့ အမှားများ
Chained assignment နဲ့ value ပြင်ခြင်း
df[df["qty"] > 2]["price"] = 0 က indexing နှစ်ဆင့် ဖြစ်ပြီး ပထမဆင့်က ယာယီ object ကို ပြန်ပေးပါတယ်။ pandas 3 ရဲ့ Copy-on-Write အောက်မှာ ဒီ assignment က original df ကို ဘယ်တော့မှ မပြောင်းပါဘူး၊ ChainedAssignmentError warning ပဲ ပေးပါတယ်။ df.loc[df["qty"] > 2, "price"] = 0 လို တစ်ဆင့်တည်းနဲ့ ရေးပါ။
Condition ပေါင်းရာမှာ and/or သုံးခြင်း
df[df.qty > 1 and df.price < 3] က 'The truth value of a Series is ambiguous' ValueError ကို ပေးပါတယ်၊ Python ရဲ့ and က Series တစ်ခုလုံးကို True/False တစ်ခုတည်း ပြောင်းဖို့ ကြိုးစားလို့ပါ။ (df.qty > 1) & (df.price < 3) လို့ ကွင်းနဲ့ ရေးပါ၊ ကွင်းမပါရင် & က comparison ထက် အရင် အလုပ်လုပ်ပါတယ်။
Filter လုပ်ပြီးနောက် index ကို မေ့ခြင်း
Filter လုပ်ထားတဲ့ ဇယားက မူရင်း label တွေကို ထိန်းထားလို့ big.loc[0] က KeyError ပေးနိုင်ပါတယ်။ Position အလိုက်လိုရင် iloc[0] ကို သုံးပါ၊ 0 ကနေ ပြန်စချင်ရင် reset_index(drop=True) ကို ခေါ်ပါ။
Best Practices
Best practices
- File ဖတ်ပြီးတာနဲ့ shape, dtypes နဲ့ isna().sum() ကို ချက်ချင်း စစ်ပါ။
- Row ပေါ်မှာ iterrows() နဲ့ loop ပတ်တာကို ရှောင်ပြီး column expression ဒါမှမဟုတ် groupby ကို သုံးပါ။
- Value ပြင်တဲ့အခါ loc[row, column] ကို တစ်ဆင့်တည်း သုံးပါ။
- Cleaning အဆင့်တွေကို DataFrame အသစ် ပြန်ပေးတဲ့ function တွေအဖြစ် ရေးပြီး input ကို မပြင်ပါနဲ့။
Mini challenge
Mini challenge: team timesheet report
Team သုံးခုရဲ့ timesheet ကို DataFrame အဖြစ် ပေးထားပါတယ်၊ တစ်ယောက်ရဲ့ hours က missing ဖြစ်နေပါတယ်။ Missing hours ကို 0 ဖြည့်ပြီး pay column ထည့်တဲ့ clean function၊ team အလိုက် လူဦးရေ၊ hours နဲ့ pay စုစုပေါင်းကို ထုတ်တဲ့ team_report function ကို ရေးပါ။ ပြီးရင် overtime လုပ်တဲ့သူတွေနဲ့ team တစ်ခုစီက လစာ အများဆုံး ရသူကို ပြပါ။
- clean က input ကို မပြင်ဘဲ DataFrame အသစ် ပြန်ပေးရမယ်
- team_report က named aggregation နဲ့ people, hours, pay column တွေ ထုတ်ပြီး pay အလိုက် စီရမယ်
- hours 38 ကျော်တဲ့သူတွေကို loc နဲ့ ရွေးပါ
- team တစ်ခုစီရဲ့ pay အများဆုံး row ကို groupby + idxmax နဲ့ ရှာပါ
import pandas as pd
timesheet = pd.DataFrame({
"name": ["Aye", "Ko Ko", "Mya", "Zaw", "Hla", "Nandar"],
"team": ["web", "web", "data", "data", "data", "ops"],
"hours": [38, None, 42, 35, 40, 30],
"rate": [12.0, 11.5, 15.0, 14.0, 15.0, 10.0],
})
def clean(df: pd.DataFrame) -> pd.DataFrame:
# TODO: copy-safe fill of missing hours with 0, then add pay = hours * rate
...
def team_report(df: pd.DataFrame) -> pd.DataFrame:
# TODO: groupby team -> people (count), hours (sum), pay (sum), sorted by pay
...
# TODO: print missing counts before/after, the report,
# the overtime rows (hours > 38) and the top earner per teamရလဒ်: Missing 1 ကနေ 0 ဖြစ်သွားရမယ်၊ report မှာ data team က pay 1720.0 နဲ့ ထိပ်ဆုံး ရောက်ပြီး web 456.0၊ ops 300.0 လိုက်ရပါမယ်။ Overtime မှာ Mya (42.0) နဲ့ Hla (40.0) ပါပြီး team အလိုက် အများဆုံးက Mya, Nandar, Aye ဖြစ်ရပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
df.assign(hours=df["hours"].fillna(0)) က DataFrame အသစ်ကို ပြန်ပေးပါတယ်။ Named aggregation က agg(people=("name", "count")) ပုံစံပါ။ groupby("team")["pay"].idxmax() က index label တွေကို ပြန်ပေးလို့ loc ထဲ တိုက်ရိုက် ထည့်လို့ ရပါတယ်။
အဖြေ ကြည့်ရန်
import pandas as pd
timesheet = pd.DataFrame({
"name": ["Aye", "Ko Ko", "Mya", "Zaw", "Hla", "Nandar"],
"team": ["web", "web", "data", "data", "data", "ops"],
"hours": [38, None, 42, 35, 40, 30],
"rate": [12.0, 11.5, 15.0, 14.0, 15.0, 10.0],
})
def clean(df: pd.DataFrame) -> pd.DataFrame:
"""Return a new frame: missing hours become 0, plus a pay column."""
out = df.assign(hours=df["hours"].fillna(0))
out["pay"] = out["hours"] * out["rate"]
return out
def team_report(df: pd.DataFrame) -> pd.DataFrame:
return (
df.groupby("team")
.agg(people=("name", "count"), hours=("hours", "sum"), pay=("pay", "sum"))
.sort_values("pay", ascending=False)
)
sheet = clean(timesheet)
print("missing before:", int(timesheet["hours"].isna().sum()),
"after:", int(sheet["hours"].isna().sum()))
print(team_report(sheet))
overtime = sheet.loc[sheet["hours"] > 38, ["name", "hours"]]
print(overtime.to_string(index=False))
top = sheet.loc[sheet.groupby("team")["pay"].idxmax(), ["team", "name", "pay"]]
print(top.to_string(index=False))Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- DataFrame က index၊ column နာမည်တွေနဲ့ dtype ကိုယ်ပိုင်ရှိတဲ့ column array တွေ ပါဝင်တဲ့ ဇယားပါ။
- String နဲ့ ရွေးရင် Series၊ list နဲ့ ရွေးရင် DataFrame ရပြီး row နဲ့ column တွဲရွေးဖို့ loc/iloc ကို သုံးပါ။
- Filter condition တွေကို & နဲ့ | သုံးပြီး ကွင်းထဲ ထည့်ရေးပါ။
- groupby က split-apply-combine ဖြစ်ပြီး value ပြင်တဲ့အခါ chained assignment အစား loc ကို သုံးပါ။
pandas — Getting Started — pandas