Python for data · lesson 9 of 11
Parts in this lesson
Apd.read_csv("penguins.csv")a table from a CSV file
Bdf.info(), df.describe()what each column holds
Cdf[df["species"] == "Gentoo"]0.3: a mask, on a table
Ddf.dropna(subset=features)drop rows missing a feature
Edf[features].to_numpy()from pandas to NumPy

Tables with pandas

Last updated

Real data arrives as a table with named columns of different kinds: species as text, measurements as decimals, some cells empty. NumPy wants one type for everything, so you load and clean the table with pandas first, then hand the numbers to NumPy for the model. In this lesson you'll load a CSV, look at it, pick rows and columns, deal with missing values, and turn it into the X and y every model in this course is trained on.

By the end of this lesson you can

  • Load a CSV into a DataFrame and look at it with head, info and describe
  • Choose columns, and rows that meet a condition
  • Find missing values and drop the rows that are missing what you need
  • Turn a DataFrame into a feature matrix X and a label array y

Load and look

pandas is the Python library for tables. Its table is a DataFrame: rows, and named columns, each column with its own type. Load the full penguins file from lesson 0.8 and look at it four ways. Run each cell:

penguins.ipynb
  • pd.read_csv reads the file into a DataFrame, and head() shows its first five rows. NA in the file became NaN, pandas' mark for a missing value.
  • shape is (344, 8): 344 penguins, 8 columns. The same idea as a NumPy shape.
  • info() lists each column with how many values are not missing and its type. str columns hold text; float64 columns hold decimals; year is whole numbers (int64). Four measurements have 342 values out of 344, and sex has 333.
  • describe() summarises every number column: count, mean, standard deviation, minimum, quartiles and maximum. Look for anything strange here first. A minimum flipper length of 0 mm, or a mass in the millions, would mean bad data.

info() and describe() are the first two lines of every new dataset you open. They take a second and catch problems that would take a day to find from a model's odd results.

Choosing columns and rows

Picking from a DataFrame uses column names instead of positions. Run each cell:

choose.ipynb
  • penguins["species"] is one column: a Series. value_counts() counts each value: 152 Adelie, 124 Gentoo, 68 Chinstrap. The classes aren't the same size, and Stage 2 shows why that matters when you measure a classifier.
  • A list of names in the brackets, penguins[["flipper_length_mm", "body_mass_g"]], gives a smaller DataFrame. Note the double brackets: the outer pair picks, the inner pair is the list.
  • A mask picks rows, exactly as in lesson 0.3: penguins["species"] == "Gentoo" is True or False for each row, and penguins[...] keeps the True ones.
  • .mean() on a column works like NumPy's. Gentoo penguins weigh 5,076 g on average.

Missing values, and X and y

Most models can't train on a missing value: the maths has no number to use. Step through how to find them:

Finding the missing values in a table. The week’s sales file as a map: every cell a box, ten rows by five columns. The dark boxes are missing.weekdatestorekilospricenote0123456789
1 of 4 The week’s sales file as a map: every cell a box, ten rows by five columns. The dark boxes are missing.

Now for the penguins:

missing.ipynb
  • isna().sum() counts the missing values in each column: 2 in each measurement, 11 in sex.
  • dropna() drops every row with any missing value: 344 rows become 333. But 9 of the 11 dropped penguins only lacked sex, and if your model doesn't use sex, you've thrown away 9 good examples.
  • dropna(subset=features) only looks at the columns you name, so it drops just the 2 penguins with no measurements: 342 rows kept.

Then the last move of every data-loading step in this course:

  • X = kept[features].to_numpy() is the feature matrix: shape (342, 3), all float64, ready for @ and everything else in this stage.
  • y = kept["species"].to_numpy() is the label array: what the model should learn to predict, one per row of X.

X and y must stay lined up: row i of X and value i of y are the same penguin. That's why the rows are dropped before splitting them, from one table.

Wrong way: numbers stored as text

Someone typed penguin masses into a spreadsheet, and where a scale broke they wrote unknown. Load it and take the mean:

masses.ipynb

The first cell shows the trouble: the column's type is a string type, not a number. One word in a column of numbers made pandas read the whole column as text, because a column has one type, like a NumPy array. Then mean() fails with a TypeError: you can't average text.

This one is lucky, because it crashes. If you'd converted the column to NumPy and then to numbers some other way, you could get strings sorted as text ("10" < "9") or a model that won't accept the data, far from the cause.

The fix is pd.to_numeric with errors="coerce": everything that's a number becomes one, and everything else becomes NaN, a missing value you can count and decide about (step 3). The mean of the four real masses is 3,662.5 g. Whenever info() shows a text type on a column that should hold numbers, look for the value that isn't one.

Check what you learned

df.info() shows a column with 500 entries but 470 non-null. What does that mean?
Your model uses three measurement columns. Which keeps the most usable rows?
Predict, then try it in step 2’s notebook: what shape is penguins[["species", "island"]]?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning