pandas למתחיליםpandas for beginners
DataFrame, סינון, קיבוץ וסטטיסטיקה.
DataFrame, filtering, grouping and statistics.
01DataFrame ראשוןYour first DataFrame
pandas היא הספרייה שבזכותה פייתון היא שפת הנתונים של העולם. pd.read_csv קורא קובץ לDataFrame, טבלה עם עמודות בשמות. במקום לולאות, כותבים פעולה אחת על עמודה שלמה. head() מראה את השורות הראשונות ו-shape את הגודל. (כאן הנתונים בתוך מחרוזת כדי שהדוגמה תרוץ בכל מקום; אצלכם: pd.read_csv("books.csv").)
pandas is the library that made Python the world's data language. pd.read_csv reads a file into a DataFrame, a table with named columns. Instead of loops, you write one operation on a whole column. head() shows the first rows and shape the size. (Here the data lives in a string so the example runs anywhere; on your machine: pd.read_csv("books.csv").)
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(df.head(3))
print(df.shape)
print(list(df.columns))title author pages year month rating 0 Dune Frank Herbert 412 1965 Jan 5 1 Emma Jane Austen 474 1815 Feb 3 2 Matilda Roald Dahl 240 1988 Feb 5 (6, 6) ['title', 'author', 'pages', 'year', 'month', 'rating']
DataFrame הוא כמו גיליון אקסל שאפשר לדבר איתו בקוד: במקום לגרור עכבר על 10,000 שורות, כותבים משפט אחד.
A DataFrame is like an Excel sheet you can talk to in code: instead of dragging a mouse over 10,000 rows, you write one sentence.
שוכחים להתקין את pandas.
Forgetting to install pandas.
import pandsa as pdTraceback (most recent call last):
File "/Users/you/python-course/first_df.py", line 1, in <module>
import pandsa as pd
ModuleNotFoundError: No module named 'pandsa'ModuleNotFoundError: No module named 'pandsa': כאן זו שגיאת כתיב. אם השם נכון ועדיין נכשל: pip install pandas בתוך ה-venv.ModuleNotFoundError: No module named 'pandsa': here it's a typo. If the name is right and it still fails: pip install pandas inside the venv.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02לבחור עמודות ושורותSelecting columns and rows
עמודה אחת היא Series: df["pages"]. כמה עמודות, ברשימה בתוך הסוגריים: df[["title", "pages"]] (שימו לב לסוגריים הכפולים). לשורות לפי מספר iloc, ולפי תווית loc. ועל Series אפשר לחשב מיד: .mean(), .max(), .sum().
One column is a Series: df["pages"]. Several columns go in a list inside the brackets: df[["title", "pages"]] (note the double brackets). For rows by position use iloc, by label loc. And you can compute on a Series right away: .mean(), .max(), .sum().
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))
pages = df["pages"]
print(pages.mean(), pages.max())
print(df[["title", "pages"]].tail(2))
print(df.iloc[0]["title"], "|", df.loc[2, "author"])315.5 474
title pages
4 The Hobbit 310
5 Persuasion 249
Dune | Roald Dahlעמודה ב-DataFrame היא כמו עמודה בגיליון: לוחצים על הכותרת ומקבלים את כולה, ואז אפשר לבקש סכום או ממוצע בבת אחת.
A DataFrame column is like a spreadsheet column: click the header and get all of it, then ask for a sum or average in one go.
שם עמודה לא קיים.
A column name that doesn't exist.
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(df["Pages"])Traceback (most recent call last):
File "/usr/local/lib/python3.13/site-packages/pandas/core/indexes/base.py", line 3641, in get_loc
return self._engine.get_loc(casted_key)
~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^
File "pandas/_libs/index.pyx", line 168, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 197, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 7668, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 7676, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Pages'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/you/python-course/select.py", line 13, in <module>
print(df["Pages"])
~~^^^^^^^^^
File "/usr/local/lib/python3.13/site-packages/pandas/core/frame.py", line 4378, in __getitem__
indexer = self.columns.get_loc(key)
File "/usr/local/lib/python3.13/site-packages/pandas/core/indexes/base.py", line 3648, in get_loc
raise KeyError(key) from err
KeyError: 'Pages'KeyError: 'Pages': שמות עמודות רגישים לאותיות גדולות. print(df.columns) מראה את השמות המדויקים.KeyError: 'Pages': column names are case-sensitive. print(df.columns) shows the exact names.03סינון ומיוןFiltering and sorting
df["pages"] > 300 לא מחזיר True אחד, אלא Series של True/False לכל שורה: מסכה בוליאנית. כשמכניסים אותה לסוגריים, נשארות רק השורות עם True. לכמה תנאים משתמשים ב-& (וגם) ו-| (או), וכל תנאי בסוגריים משלו. sort_values ממיין.
df["pages"] > 300 doesn't return one True, but a Series of True/False per row: a boolean mask. Put it inside the brackets and only the True rows remain. For several conditions use & (and) and | (or), each condition in its own parentheses. sort_values sorts.
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(df["pages"] > 300)
long_books = df[df["pages"] > 300]
print(long_books["title"].tolist())
good_dahl = df[(df["author"] == "Roald Dahl") & (df["rating"] == 5)]
print(good_dahl["title"].tolist())
print(df.sort_values("year")[["title", "year"]].head(3))0 True
1 True
2 False
3 False
4 True
5 False
Name: pages, dtype: bool
['Dune', 'Emma', 'The Hobbit']
['Matilda']
title year
1 Emma 1815
5 Persuasion 1817
4 The Hobbit 1937מסכה בוליאנית היא כמו שבלונה שמניחים על הטבלה: רק השורות שמתחת לחורים נראות.
A boolean mask is like a stencil laid over the table: only the rows under the holes show through.
משתמשים ב-and במקום &.
Using and instead of &.
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(df[df["pages"] > 300 and df["rating"] == 5])Traceback (most recent call last):
File "/Users/you/python-course/filter.py", line 13, in <module>
print(df[df["pages"] > 300 and df["rating"] == 5])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.13/site-packages/pandas/core/generic.py", line 1501, in __bool__
raise ValueError(
...<2 lines>...
)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().: and מצפה ל-True יחיד. על Series משתמשים ב-& וסוגריים: (df["pages"] > 300) & (df["rating"] == 5).ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().: and expects a single True. On a Series use & and parentheses: (df["pages"] > 300) & (df["rating"] == 5).04עמודות חדשותNew columns
יוצרים עמודה חדשה בהשמה, והחישוב רץ על כל השורות בלי לולאה. לפעולות טקסט יש .str: df["author"].str.upper(). ולכל דבר אחר, .apply(פונקציה) מריץ פונקציה שלכם על כל ערך.
Create a new column by assignment, and the calculation runs on every row without a loop. For text there's .str: df["author"].str.upper(). For anything else, .apply(function) runs your function on each value.
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["hours"] = (df["pages"] / 40).round(1)
df["last_name"] = df["author"].str.split().str[-1]
df["era"] = df["year"].apply(lambda y: "classic" if y < 1900 else "modern")
print(df[["title", "hours", "last_name", "era"]])title hours last_name era 0 Dune 10.3 Herbert modern 1 Emma 11.8 Austen classic 2 Matilda 6.0 Dahl modern 3 The BFG 5.2 Dahl modern 4 The Hobbit 7.8 Tolkien modern 5 Persuasion 6.2 Austen classic
עמודה מחושבת היא כמו נוסחה שגוררים לאורך כל העמודה באקסל: כותבים פעם אחת, וכל שורה מקבלת את התוצאה שלה.
A computed column is like a formula dragged down a whole Excel column: write it once, and every row gets its own result.
מחברים מספר למחרוזת בעמודה.
Adding a number to a string column.
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(df["title"] + 1)Traceback (most recent call last):
File "/Users/you/python-course/new_cols.py", line 13, in <module>
print(df["title"] + 1)
~~~~~~~~~~~~^~~
File "/usr/local/lib/python3.13/site-packages/pandas/core/ops/common.py", line 85, in new_method
return method(self, other)
File "/usr/local/lib/python3.13/site-packages/pandas/core/arraylike.py", line 190, in __add__
return self._arith_method(other, operator.add)
~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.13/site-packages/pandas/core/series.py", line 6751, in _arith_method
return base.IndexOpsMixin._arith_method(self, other, op)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.13/site-packages/pandas/core/base.py", line 1644, in _arith_method
result = ops.arithmetic_op(lvalues, rvalues, op)
File "/usr/local/lib/python3.13/site-packages/pandas/core/ops/array_ops.py", line 279, in arithmetic_op
res_values = op(left, right)
File "/usr/local/lib/python3.13/site-packages/pandas/core/ops/common.py", line 85, in new_method
return method(self, other)
File "/usr/local/lib/python3.13/site-packages/pandas/core/arraylike.py", line 190, in __add__
return self._arith_method(other, operator.add)
~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.13/site-packages/pandas/core/arrays/string_.py", line 1233, in _cmp_method
result[valid] = op(self._ndarray[valid], other)
~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: can only concatenate str (not "int") to strTypeError: אי אפשר לחבר מספר לטקסט. ממירים קודם: df["title"] + " (" + df["year"].astype(str) + ")".TypeError: you can't add a number to text. Convert first: df["title"] + " (" + df["year"].astype(str) + ")".05groupby: סיכום לפי קבוצותgroupby: summary by group
groupby מחלק את הטבלה לקבוצות (למשל לפי סופר) ומסכם כל אחת: סכום, ממוצע, ספירה. agg מאפשר כמה סיכומים בבת אחת. ו-value_counts() הוא הדרך המהירה לספור כמה פעמים מופיע כל ערך. זה בדיוק מה שנצטרך לגרף הקריאה החודשי במפגש הבא.
groupby splits the table into groups (e.g. by author) and summarises each: sum, mean, count. agg gives several summaries at once. And value_counts() is the quick way to count how often each value appears. That's exactly what we'll need for next session's monthly reading chart.
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(df.groupby("author")["pages"].sum().sort_values(ascending=False))
print(df.groupby("author").agg(books=("title", "count"), avg_rating=("rating", "mean")))
print(df["month"].value_counts(sort=False))author
Jane Austen 723
Roald Dahl 448
Frank Herbert 412
J. R. R. Tolkien 310
Name: pages, dtype: int64
books avg_rating
author
Frank Herbert 1 5.0
J. R. R. Tolkien 1 5.0
Jane Austen 2 3.5
Roald Dahl 2 4.5
month
Jan 1
Feb 2
Mar 2
Apr 1
Name: count, dtype: int64groupby הוא כמו למיין חשבוניות לתיקיות לפי ספק, ואז לרשום על כל תיקייה את הסכום הכולל.
groupby is like sorting receipts into folders by supplier, then writing each folder's total on the front.
שם עמודה שגוי בתוך groupby.
A wrong column name inside groupby.
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.groupby("writer")["pages"].sum()Traceback (most recent call last):
File "/Users/you/python-course/group.py", line 13, in <module>
df.groupby("writer")["pages"].sum()
~~~~~~~~~~^^^^^^^^^^
File "/usr/local/lib/python3.13/site-packages/pandas/util/_decorators.py", line 336, in wrapper
return func(*args, **kwargs)
File "/usr/local/lib/python3.13/site-packages/pandas/core/frame.py", line 10835, in groupby
return DataFrameGroupBy(
obj=self,
...<6 lines>...
dropna=dropna,
)
File "/usr/local/lib/python3.13/site-packages/pandas/core/groupby/groupby.py", line 1095, in __init__
grouper, exclusions, obj = get_grouper(
~~~~~~~~~~~^
obj,
^^^^
...<4 lines>...
dropna=self.dropna,
^^^^^^^^^^^^^^^^^^^
)
^
File "/usr/local/lib/python3.13/site-packages/pandas/core/groupby/grouper.py", line 901, in get_grouper
raise KeyError(gpr)
KeyError: 'writer'KeyError: 'writer': אין עמודה כזו. העמודה נקראת author.KeyError: 'writer': there's no such column. It's called author.groupby עושה את מה שהלולאה הזאת עושה, רק מהר.
groupby does what this loop does, only faster.
sales = [("red", 5), ("blue", 3), ("red", 2)]
totals = {}
for team, n in sales:
totals[team] = totals.get(team, 0) + n
print(totals){'red': 7, 'blue': 3}צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06ניקוי וייצואCleaning and exporting
נתונים אמיתיים מלוכלכים: תאים ריקים, רווחים, כפילויות. pandas מסמן ערך חסר כ-NaN. isna().sum() סופר חסרים בכל עמודה, fillna ממלא ו-dropna מוחק שורות. drop_duplicates מסיר כפילויות. בסוף, to_csv שומר את התוצאה הנקייה (index=False כדי לא לשמור את מספרי השורות).
Real data is messy: empty cells, spaces, duplicates. pandas marks a missing value as NaN. isna().sum() counts missing per column, fillna fills and dropna drops rows. drop_duplicates removes duplicates. Finally, to_csv saves the clean result (index=False to skip the row numbers).
import io
import pandas as pd
messy = "title,author,pages\nDune,Frank Herbert,412\nEmma,,474\n Dune ,Frank Herbert,412\nMatilda,Roald Dahl,\n"
df = pd.read_csv(io.StringIO(messy))
print(df.isna().sum())
df["title"] = df["title"].str.strip()
df["author"] = df["author"].fillna("unknown")
df = df.drop_duplicates().dropna(subset=["pages"])
df["pages"] = df["pages"].astype(int)
print(df)
df.to_csv("clean.csv", index=False)
print(open("clean.csv").read())title 0 author 1 pages 1 dtype: int64 title author pages 0 Dune Frank Herbert 412 1 Emma unknown 474 title,author,pages Dune,Frank Herbert,412 Emma,unknown,474
לנקות נתונים זה כמו לשטוף ירקות לפני בישול: לא מרגש, אבל אם מדלגים, כל המנה יוצאת לא טובה.
Cleaning data is like washing vegetables before cooking: not exciting, but skip it and the whole dish suffers.
ממירים ל-int עמודה שיש בה ערכים חסרים.
Converting a column with missing values to int.
import io
import pandas as pd
df = pd.read_csv(io.StringIO("title,pages\nDune,412\nEmma,\nMatilda,240\n"))
print(df["pages"].astype(int))Traceback (most recent call last):
File "/Users/you/python-course/clean.py", line 4, in <module>
print(df["pages"].astype(int))
~~~~~~~~~~~~~~~~~~^^^^^
File "/usr/local/lib/python3.13/site-packages/pandas/core/generic.py", line 6529, in astype
new_data = self._mgr.astype(dtype=dtype, errors=errors)
File "/usr/local/lib/python3.13/site-packages/pandas/core/internals/managers.py", line 627, in astype
return self.apply("astype", dtype=dtype, errors=errors)
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.13/site-packages/pandas/core/internals/managers.py", line 445, in apply
applied = getattr(b, f)(**kwargs)
File "/usr/local/lib/python3.13/site-packages/pandas/core/internals/blocks.py", line 607, in astype
new_values = astype_array_safe(values, dtype, errors=errors)
File "/usr/local/lib/python3.13/site-packages/pandas/core/dtypes/astype.py", line 240, in astype_array_safe
new_values = astype_array(values, dtype, copy=copy)
File "/usr/local/lib/python3.13/site-packages/pandas/core/dtypes/astype.py", line 185, in astype_array
values = _astype_nansafe(values, dtype, copy=copy)
File "/usr/local/lib/python3.13/site-packages/pandas/core/dtypes/astype.py", line 102, in _astype_nansafe
return _astype_float_to_int_nansafe(arr, dtype, copy)
File "/usr/local/lib/python3.13/site-packages/pandas/core/dtypes/astype.py", line 146, in _astype_float_to_int_nansafe
raise IntCastingNaNError(
...<3 lines>...
)
pandas.errors.IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer.Replace or remove non-finite values or cast to an integer typethat supports these values (e.g. 'Int64')pandas.errors.IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer: קודם מטפלים בחסרים (dropna או fillna(0)), ורק אז ממירים.pandas.errors.IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer: deal with missing values first (dropna or fillna(0)), then convert.סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.