נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
24
חלקPart 4: נתונים ורשתData & the web כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

pandas למתחיליםpandas for beginners

DataFrame, סינון, קיבוץ וסטטיסטיקה.

DataFrame, filtering, grouping and statistics.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

הצצה בנתוניםA first look

תזכורת: מה ביקשוReminder: the task

קראו את הנתונים לתוך df והדפיסו: מספר השורות, את הכותרת של הספר הארוך ביותר (idxmax), ואת ממוצע הדירוג מעוגל ל-2.

Read the data into df and print: the number of rows, the title of the longest book (idxmax), and the average rating rounded to 2.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import io
import pandas as pd

data = """title,author,pages,year,month,rating
Dune,Frank Herbert,412,1965,Jan,5
Emma,Jane Austen,474,1815,Feb,3
Matilda,Roald Dahl,240,1988,Feb,5
The BFG,Roald Dahl,208,1982,Mar,4
The Hobbit,J. R. R. Tolkien,310,1937,Mar,5
Persuasion,Jane Austen,249,1817,Apr,4
"""
df = pd.read_csv(io.StringIO(data))
print(len(df))
print(df.loc[df["pages"].idxmax(), "title"])
print(round(df["rating"].mean(), 2))
פלטOutput
6
Emma
4.33

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

סינוןFiltering

תזכורת: מה ביקשוReminder: the task

החזירו מ-picks(df) רשימת כותרות של ספרים עם דירוג 4 ומעלה ופחות מ-300 עמודים, ממוינות לפי מספר עמודים מהקצר לארוך.

Return from picks(df) the titles of books rated 4+ with fewer than 300 pages, sorted by pages shortest first.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import io
import pandas as pd

data = """title,author,pages,year,month,rating
Dune,Frank Herbert,412,1965,Jan,5
Emma,Jane Austen,474,1815,Feb,3
Matilda,Roald Dahl,240,1988,Feb,5
The BFG,Roald Dahl,208,1982,Mar,4
The Hobbit,J. R. R. Tolkien,310,1937,Mar,5
Persuasion,Jane Austen,249,1817,Apr,4
"""
df = pd.read_csv(io.StringIO(data))

def picks(df):
    mask = (df["rating"] >= 4) & (df["pages"] < 300)
    return df[mask].sort_values("pages")["title"].tolist()

print(picks(df))
פלטOutput
['The BFG', 'Matilda', 'Persuasion']

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

עמודה מחושבתA computed column

תזכורת: מה ביקשוReminder: the task

הוסיפו ל-df עמודה age (גיל הספר ב-2026) ועמודה size שהיא "short" מתחת ל-250 עמודים, אחרת "long". הדפיסו title, age, size לשלושת הספרים הוותיקים ביותר.

Add to df a column age (the book's age in 2026) and a column size that's "short" under 250 pages, otherwise "long". Print title, age, size for the three oldest books.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import io
import pandas as pd

data = """title,author,pages,year,month,rating
Dune,Frank Herbert,412,1965,Jan,5
Emma,Jane Austen,474,1815,Feb,3
Matilda,Roald Dahl,240,1988,Feb,5
The BFG,Roald Dahl,208,1982,Mar,4
The Hobbit,J. R. R. Tolkien,310,1937,Mar,5
Persuasion,Jane Austen,249,1817,Apr,4
"""
df = pd.read_csv(io.StringIO(data))
df["age"] = 2026 - df["year"]
df["size"] = df["pages"].apply(lambda p: "short" if p < 250 else "long")
print(df.sort_values("age", ascending=False)[["title", "age", "size"]].head(3).to_string(index=False))
פלטOutput
     title  age  size
      Emma  211  long
Persuasion  209 short
The Hobbit   89  long

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

לפי חודשBy month

תזכורת: מה ביקשוReminder: the task

כתבו per_month(df) שמחזירה מילון: חודש → מספר עמודים שנקראו, בסדר החודשים כפי שהם מופיעים בנתונים (sort=False). השתמשו ב-groupby.

Write per_month(df) returning a dict: month → pages read, in the order months appear in the data (sort=False). Use groupby.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import io
import pandas as pd

data = """title,author,pages,year,month,rating
Dune,Frank Herbert,412,1965,Jan,5
Emma,Jane Austen,474,1815,Feb,3
Matilda,Roald Dahl,240,1988,Feb,5
The BFG,Roald Dahl,208,1982,Mar,4
The Hobbit,J. R. R. Tolkien,310,1937,Mar,5
Persuasion,Jane Austen,249,1817,Apr,4
"""
df = pd.read_csv(io.StringIO(data))

def per_month(df):
    return {k: int(v) for k, v in df.groupby("month", sort=False)["pages"].sum().items()}

print(per_month(df))
פלטOutput
{'Jan': 412, 'Feb': 714, 'Mar': 518, 'Apr': 249}

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

מדף, צעד 24: סטטיסטיקת קריאהShelf, step 24: reading statistics

תזכורת: מה ביקשוReminder: the task

כתבו stats(df) שמחזירה מילון עם: books (כמות), pages (סך עמודים), top_author (הסופר עם הכי הרבה עמודים), best_month (החודש עם הכי הרבה עמודים), ו-avg_rating (מעוגל ל-1).

Write stats(df) returning a dict with: books (count), pages (total pages), top_author (the author with the most pages), best_month (the month with the most pages), and avg_rating (rounded to 1).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
stats.py
import io
import pandas as pd

data = """title,author,pages,year,month,rating
Dune,Frank Herbert,412,1965,Jan,5
Emma,Jane Austen,474,1815,Feb,3
Matilda,Roald Dahl,240,1988,Feb,5
The BFG,Roald Dahl,208,1982,Mar,4
The Hobbit,J. R. R. Tolkien,310,1937,Mar,5
Persuasion,Jane Austen,249,1817,Apr,4
"""
df = pd.read_csv(io.StringIO(data))

def stats(df):
    return {
        "books": int(len(df)),
        "pages": int(df["pages"].sum()),
        "top_author": df.groupby("author")["pages"].sum().idxmax(),
        "best_month": df.groupby("month")["pages"].sum().idxmax(),
        "avg_rating": round(float(df["rating"].mean()), 1),
    }

for k, v in stats(df).items():
    print(f"{k}: {v}")
פלטOutput
books: 6
pages: 1893
top_author: Jane Austen
best_month: Feb
avg_rating: 4.3

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

ניקוי אמיתיReal cleaning

תזכורת: מה ביקשוReminder: the task

כתבו clean(text) שמקבלת CSV מלוכלך (עמודות title, author, pages, rating) ומחזירה DataFrame נקי: כותרות וסופרים בלי רווחים מסביב, סופר חסר → unknown, שורות בלי pages נמחקות, pages כ-int, rating חסר → ממוצע הדירוגים (מעוגל ל-1), וכפילויות לפי title נמחקות (נשאר הראשון).

Write clean(text) taking a messy CSV (columns title, author, pages, rating) and returning a clean DataFrame: titles and authors stripped, missing author → unknown, rows without pages dropped, pages as int, missing rating → the mean rating (rounded to 1), and duplicates by title dropped (keep the first).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import io
import pandas as pd

def clean(text):
    df = pd.read_csv(io.StringIO(text))
    df["title"] = df["title"].str.strip()
    df["author"] = df["author"].str.strip().fillna("unknown")
    df = df.dropna(subset=["pages"]).drop_duplicates(subset="title").copy()
    df["pages"] = df["pages"].astype(int)
    df["rating"] = df["rating"].fillna(round(df["rating"].mean(), 1))
    return df.reset_index(drop=True)

messy = "title,author,pages,rating\n Dune ,Frank Herbert,412,5\nEmma,,474,\nDune,Frank Herbert,412,4\nMatilda, Roald Dahl ,240,4\nGhost,Someone,,3\n"
print(clean(messy).to_string(index=False))
פלטOutput
  title        author  pages  rating
   Dune Frank Herbert    412     5.0
   Emma       unknown    474     4.5
Matilda    Roald Dahl    240     4.0

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

טבלת צירA pivot table

תזכורת: מה ביקשוReminder: the task

כתבו pivot(df) שמחזירה טבלה שבה כל שורה היא סופר, כל עמודה היא חודש (בסדר Jan, Feb, Mar, Apr), והערכים הם סכום עמודים (0 כשאין). השתמשו ב-pivot_table עם fill_value=0.

Write pivot(df) returning a table where each row is an author, each column a month (in order Jan, Feb, Mar, Apr), and values are page totals (0 where none). Use pivot_table with fill_value=0.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import io
import pandas as pd

data = """title,author,pages,year,month,rating
Dune,Frank Herbert,412,1965,Jan,5
Emma,Jane Austen,474,1815,Feb,3
Matilda,Roald Dahl,240,1988,Feb,5
The BFG,Roald Dahl,208,1982,Mar,4
The Hobbit,J. R. R. Tolkien,310,1937,Mar,5
Persuasion,Jane Austen,249,1817,Apr,4
"""
df = pd.read_csv(io.StringIO(data))

def pivot(df):
    t = df.pivot_table(index="author", columns="month", values="pages", aggfunc="sum", fill_value=0)
    return t[["Jan", "Feb", "Mar", "Apr"]]

print(pivot(df))
פלטOutput
month             Jan  Feb  Mar  Apr
author                              
Frank Herbert     412    0    0    0
J. R. R. Tolkien    0    0  310    0
Jane Austen         0  474    0  249
Roald Dahl          0  240  208    0

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

נבנה על ידיBuilt by Ariel Yohimovich