נבנה על ידי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.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • import pandas as pdimport pandas as pd
  • pd.read_csv → DataFramepd.read_csv → a DataFrame
  • df["title"] → Seriesdf["title"] → a Series
  • df[["title", "pages"]] → טבלה קטנהdf[["title", "pages"]] → a smaller table
  • df[df["pages"] > 300]: מסכהdf[df["pages"] > 300]: a mask
  • & ו-| עם סוגריים& and | with parentheses
  • df["hours"] = df["pages"] / 40df["hours"] = df["pages"] / 40
  • פעולה על עמודה שלמה בבת אחתOne operation on a whole column at once
  • df.groupby("author")["pages"].sum()df.groupby("author")["pages"].sum()

מונחיםTerms

  • pandaspandas: ספרייה לעבודה עם טבלאות נתונים בפייתון: קריאה, סינון, סיכום וייצוא. מתקינים עם pip install pandas.A library for working with data tables in Python: reading, filtering, summarising and exporting. Install with pip install pandas.
  • DataFrameDataFrame: טבלה של pandas: שורות ועמודות עם שמות, כמו גיליון אקסל בתוך פייתון.A pandas table: named rows and columns, like an Excel sheet inside Python.
  • SeriesSeries: עמודה אחת של DataFrame: רשימת ערכים עם אינדקס.One column of a DataFrame: a list of values with an index.
  • מסכה בוליאניתboolean mask: Series של True/False שבוחרת שורות: df[df["pages"] > 300].A Series of True/False that picks rows: df[df["pages"] > 300].
  • groupbygroupby: חלוקת טבלה לקבוצות לפי עמודה וסיכום כל קבוצה, כמו GROUP BY ב-SQL.Splitting a table into groups by a column and summarising each, like GROUP BY in SQL.
  • NaNNaN: "Not a Number": הסימן של pandas לערך חסר."Not a Number": pandas' marker for a missing value.

Cheatsheet

DataFrameDataFrame
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
בחירהSelection
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
סינוןFiltering
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
חישוביםCalculations
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
groupbygroupby
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
ניקויCleaning
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()

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
ModuleNotFoundErrorשוכחים להתקין את pandas.Forgetting to install pandas.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.
KeyErrorשם עמודה לא קיים.A column name that doesn't exist.KeyError: 'Pages': שמות עמודות רגישים לאותיות גדולות. print(df.columns) מראה את השמות המדויקים.KeyError: 'Pages': column names are case-sensitive. print(df.columns) shows the exact names.
ValueErrorמשתמשים ב-and במקום &.Using and instead of &.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).
TypeErrorמחברים מספר למחרוזת בעמודה.Adding a number to a string column.TypeError: אי אפשר לחבר מספר לטקסט. ממירים קודם: df["title"] + " (" + df["year"].astype(str) + ")".TypeError: you can't add a number to text. Convert first: df["title"] + " (" + df["year"].astype(str) + ")".
KeyErrorשם עמודה שגוי בתוך groupby.A wrong column name inside groupby.KeyError: 'writer': אין עמודה כזו. העמודה נקראת author.KeyError: 'writer': there's no such column. It's called author.
pandas.errors.IntCastingNaNErrorממירים ל-int עמודה שיש בה ערכים חסרים.Converting a column with missing values to int.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.

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