🤖 Ask PyProf.

גישה לנתונים בטבלה#

עכשיו כשהטבלה קיימת, נרצה לבחור ממנה חלקים: עמודה אחת, כמה עמודות, שורות מסוימות, או תא יחיד. נתחיל מהדרך הפשוטה ביותר ונוסיף בהדרגה עוד אפשרויות.

Note

אפשר להוריד את קובץ הנתונים לעבודה עצמאית: compound_phase_points.csv.

import pandas as pd

pd.options.display.max_rows = 8
pd.options.display.max_columns = 8

df = pd.read_csv("files/compound_phase_points.csv")
display(df)
compound formula family molar_mass_g_mol melting_point_C boiling_point_C polarity
0 water H2O inorganic 18.02 0.0 100.0 polar
1 methanol CH4O alcohol 32.04 -97.6 64.7 polar
2 ethanol C2H6O alcohol 46.07 -114.1 78.4 polar
3 1-propanol C3H8O alcohol 60.10 -126.0 97.2 polar
... ... ... ... ... ... ... ...
12 ethane C2H6 alkane 30.07 -182.8 -88.6 nonpolar
13 butane C4H10 alkane 58.12 -138.3 -0.5 nonpolar
14 naphthalene C10H8 aromatic 128.17 80.2 218.0 nonpolar
15 benzoic acid C7H6O2 carboxylic acid 122.12 122.4 249.2 polar

16 rows × 7 columns

בחירת עמודה אחת בעזרת []#

כאשר כותבים שם עמודה בתוך סוגריים מרובעים, מקבלים את העמודה הזאת בלבד. התוצאה היא Series, כלומר סדרה חד־ממדית.

boiling_points = df["boiling_point_C"]
print(type(boiling_points))
display(boiling_points)
<class 'pandas.Series'>
0     100.0
1      64.7
2      78.4
3      97.2
      ...  
12    -88.6
13     -0.5
14    218.0
15    249.2
Name: boiling_point_C, Length: 16, dtype: float64

הסדרה שומרת את שמות השורות המקוריים, אבל יש לה רק ציר אחד. אין בה גם שורות וגם עמודות כמו בטבלה.

בחירת כמה עמודות#

כדי לבחור כמה עמודות, מעבירים רשימה של שמות עמודות. במקרה כזה התוצאה היא שוב DataFrame, כי נשארה לנו טבלה דו־ממדית.

phase_columns = df[["compound", "melting_point_C", "boiling_point_C"]]
display(phase_columns)
compound melting_point_C boiling_point_C
0 water 0.0 100.0
1 methanol -97.6 64.7
2 ethanol -114.1 78.4
3 1-propanol -126.0 97.2
... ... ... ...
12 ethane -182.8 -88.6
13 butane -138.3 -0.5
14 naphthalene 80.2 218.0
15 benzoic acid 122.4 249.2

16 rows × 3 columns

בחירה לפי שמות בעזרת loc#

loc בוחרת לפי שמות. התחביר הכללי הוא:

df.loc[rows, columns]

נבחר את שם התרכובת ואת נקודת הרתיחה עבור השורות הראשונות בטבלה:

display(df.loc[0:4, ["compound", "boiling_point_C"]])
compound boiling_point_C
0 water 100.0
1 methanol 64.7
2 ethanol 78.4
3 1-propanol 97.2
4 acetone 56.1

שימו לב: ב־loc, כאשר משתמשים בטווח של שמות שורות, הקצה הימני כלול. לכן 0:4 מחזיר גם את שורה 4. זוהי התנהגות שונה מ־slicing רגיל ברשימות וב־NumPy.

אפשר להשתמש ב־loc גם כדי לבחור תא יחיד לפי שם שורה ושם עמודה:

print(df.loc[0, "compound"])
print(df.loc[0, "boiling_point_C"])
water
100.0

בחירה לפי מיקום בעזרת iloc#

iloc בוחרת לפי מיקום מספרי, בדומה לרשימות ולמערכי NumPy. כאן הקצה הימני של טווח אינו כלול.

display(df.iloc[0:4, 0:3])
compound formula family
0 water H2O inorganic
1 methanol CH4O alcohol
2 ethanol C2H6O alcohol
3 1-propanol C3H8O alcohol

הבחירה למעלה אומרת: קח את ארבע השורות הראשונות ואת שלוש העמודות הראשונות. זו דרך נוחה כאשר המיקום חשוב יותר מהשם, אבל ברוב ניתוחי הנתונים עדיף לעבוד עם שמות עמודות ברורים.

שורה אחת היא Series#

אם נחלץ שורה אחת מתוך הטבלה, נקבל Series. גם כאן מדובר במבנה חד־ממדי.

row = df.loc[0]
print(type(row))
display(row)
<class 'pandas.Series'>
compound                water
formula                   H2O
family              inorganic
molar_mass_g_mol        18.02
melting_point_C           0.0
boiling_point_C         100.0
polarity                polar
Name: 0, dtype: object

מכיוון ש־row היא סדרה חד־ממדית, אפשר לבחור מתוכה ערך אחד לפי שם:

print(row["compound"])
print(row["boiling_point_C"])
water
100.0

אם ננסה לבחור מתוך הסדרה כאילו היא עדיין טבלה דו־ממדית, נקבל שגיאה. השגיאה כאן מכוונת: היא מזכירה לנו ש־Series היא חד־ממדית.

print(row.iloc[:, 0])
---------------------------------------------------------------------------
IndexingError                             Traceback (most recent call last)
Cell In[10], line 1
----> 1 print(row.iloc[:, 0])

File /opt/hostedtoolcache/Python/3.11.15/x64/lib/python3.11/site-packages/pandas/core/indexing.py:1200, in _LocationIndexer.__getitem__(self, key)
   1198     if self._is_scalar_access(key):
   1199         return self.obj._get_value(*key, takeable=self._takeable)
-> 1200     return self._getitem_tuple(key)
   1201 else:
   1202     # we by definition only have the 0th axis
   1203     axis = self.axis or 0

File /opt/hostedtoolcache/Python/3.11.15/x64/lib/python3.11/site-packages/pandas/core/indexing.py:1711, in _iLocIndexer._getitem_tuple(self, tup)
   1710 def _getitem_tuple(self, tup: tuple):
-> 1711     tup = self._validate_tuple_indexer(tup)
   1712     with suppress(IndexingError):
   1713         return self._getitem_lowerdim(tup)

File /opt/hostedtoolcache/Python/3.11.15/x64/lib/python3.11/site-packages/pandas/core/indexing.py:989, in _LocationIndexer._validate_tuple_indexer(self, key)
    984 @final
    985 def _validate_tuple_indexer(self, key: tuple) -> tuple:
    986     """
    987     Check the key for valid keys across my indexer.
    988     """
--> 989     key = self._validate_key_length(key)
    990     key = self._expand_ellipsis(key)
    991     for i, k in enumerate(key):

File /opt/hostedtoolcache/Python/3.11.15/x64/lib/python3.11/site-packages/pandas/core/indexing.py:1027, in _LocationIndexer._validate_key_length(self, key)
   1025             raise IndexingError(_one_ellipsis_message)
   1026         return self._validate_key_length(key)
-> 1027     raise IndexingError("Too many indexers")
   1028 return key

IndexingError: Too many indexers

תרגול קצר#

  1. בחרו רק את העמודות compound, family ו־molar_mass_g_mol.

  2. השתמשו ב־loc כדי להציג את התרכובות בשורות 2 עד 6, כולל.

  3. השתמשו ב־iloc כדי להציג את שלוש השורות האחרונות ואת שתי העמודות הראשונות.

# Write your code here