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,infoanddescribe - 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
Xand a label arrayy
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:
pd.read_csvreads the file into a DataFrame, andhead()shows its first five rows.NAin the file becameNaN, pandas' mark for a missing value.shapeis(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.strcolumns hold text;float64columns hold decimals;yearis whole numbers (int64). Four measurements have 342 values out of 344, andsexhas 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:
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, andpenguins[...]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:
Now for the penguins:
isna().sum()counts the missing values in each column: 2 in each measurement, 11 insex.dropna()drops every row with any missing value: 344 rows become 333. But 9 of the 11 dropped penguins only lackedsex, and if your model doesn't usesex, 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), allfloat64, 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 ofX.
and must stay lined up: row of X and value 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:
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
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.
- pandas: 10 minutes to pandas: DataFrames, head, describe, selecting columns and Boolean indexing
- pandas: pandas.read_csv: reading a CSV, and NA read as missing
- pandas: Working with missing data: isna and dropna
- pandas: pandas.to_numeric: turning text into numbers, with errors="coerce"
- pandas: pandas.DataFrame.to_numpy: a DataFrame as a NumPy array
- Horst, Hill and Gorman, palmerpenguins: Palmer Archipelago (Antarctica) penguin data, 2020: the penguins dataset, released under CC0