Sub topic 5
A first look at shape, types, and summaries
This chapter assumes you can read a pandas DataFrame, run cells in Jupyter, and recall basic statistics (mean, median, distribution). It covers the first inspection of a freshly loaded dataset: how big it is, what types pandas assigned, and what the summary statistics say. The goal is to form concrete expectations, and to find the surprises, before you clean or plot anything.
Why a first look comes before everything else
After loading the data (previous chapter), you hold a DataFrame you have not yet questioned. A first look answers four basic questions:
- How many rows and columns are there?
- What type did pandas give each column?
- How many values are present in each column?
- What range and spread do the numbers have?
Each answer is a check against what you expected. If you expected a few thousand orders and see 40 rows, or you expected dates and see strings, you want to learn that now. These checks are cheap, and they decide what the audit and cleaning steps need to cover.
The first look only observes. It never changes df_raw.
Shape: rows and columns
DataFrame.shape returns a tuple of (rows, columns). Print it right after loading, and compare it with what you know about the source, such as a row count in a database or a file listing.
import pandas as pd
df_raw = pd.read_csv("data/raw/orders.csv", parse_dates=["order_date"])
print(df_raw.shape)Note the expected values in a markdown cell. If a later step changes the row count, you can compare it with this number.
Types and non-null counts with info()
df.info() prints one line per column with its non-null count and dtype, plus total memory use. It prints directly and returns None, so do not wrap it in print().
df_raw.info()Read the output for three things.
- Non-null counts below the row count. The gap is the number of missing values in that column.
- Columns with dtype
object. In pandas,objectusually means strings, but it can also mean mixed types. A column of numbers stored asobjectoften contains a stray text value such as"N/A"or"1,200". - Date columns stored as
object. Hereparse_dateswas passed toread_csv, soorder_dateshould showdatetime64[ns]. If it showsobject, some values failed to parse and pandas left the whole column as text.
Common type surprises
| What you see | Likely cause | What to check |
|---|---|---|
| Numeric column is `object` | A text token such as `"N/A"`, `"-"`, or a currency symbol | `df["amount"].map(type).value_counts()` |
| Integer column is `float64` | Missing values (NaN is a float) | `df["col"].isna().sum()` |
| ID column is `int64` | Numeric-looking IDs lose leading zeros | Reload with `dtype={"id": "string"}` |
| Date column is `object` | Mixed formats or invalid dates | Parse with `pd.to_datetime(..., errors="coerce")` and count NaT |
| Flag column is `object` | Values such as `"Y"`, `"N"`, `"yes"` | `df["flag"].unique()` |
The integer-to-float case is easy to miss. If quantity shows float64 and you expected whole numbers, that is a hint that missing values exist, even before you count them.
Looking at actual rows
Summaries can hide problems that are obvious in a few rows. Look at the top, the bottom, and a random sample.
df_raw.head()
df_raw.tail()
df_raw.sample(5, random_state=42)Each view catches something different.
head()shows the first rows, which often reveal formatting such as casing and units.tail()can expose footer lines, totals, or truncated exports that sit at the end of a file.sample()avoids the bias of sorted files, where the first rows may all look alike. Passrandom_stateso the same rows appear on every run.
Only the last expression in a Jupyter cell is displayed. To see all three, put them in separate cells or call display() on each one.
Summary statistics with describe()
describe() gives count, mean, standard deviation, minimum, quartiles, and maximum for numeric columns. With include="all", it also summarizes non-numeric columns using count, unique, top, and freq. Transposing with .T puts one column per row, which is easier to read when there are many columns.
df_raw.describe(include="all").TBecause the numeric and non-numeric statistics share one table, many cells will be NaN. That is expected: a string column has no mean. If it is hard to read, run two separate calls.
df_raw.describe().T
df_raw.describe(include="object").TReading the numbers
Look at the relationships between statistics, not at each value alone.
- Mean far above median (the 50% row). The distribution is probably right-skewed, or a few large values pull the mean up. This is the pattern later recorded as a finding in this tutorial's order data.
- Minimum below zero where negatives make no sense. An order
amountof-40could be a refund, a data entry error, or a sentinel value. Do not decide yet. Write it down. - Maximum many times larger than the 75% quartile. Check whether this is a legitimate large order or a unit error.
countlower than the row count. That is missing data again, now seen per column.uniqueof 1 orstdof 0. The column carries no information for analysis.topandfreqon a category. Iffreqis most of the rows, the category is heavily imbalanced.
Percentiles and categorical columns
The default quartiles may be too coarse for skewed data. You can ask for more.
df_raw["amount"].describe(percentiles=[0.01, 0.05, 0.25, 0.5, 0.75, 0.95, 0.99])For a categorical column, value_counts() is more informative than describe(). Include missing values with dropna=False.
df_raw["region"].value_counts(dropna=False)This often shows variants such as "North", "north ", and "NORTH" as separate categories, which the cleaning chapter handles.
A reusable first-look cell
If you repeat the same four calls in every project, wrap them in a small function. It prints and displays but does not modify the data.
def first_look(df, n=5):
print("shape:", df.shape)
print()
df.info()
print()
display(df.head(n))
display(df.describe(include="all").T)
first_look(df_raw)display is available in Jupyter and IPython. In a plain Python script, replace it with print.
Record surprises as you go
End the first-look section with a short markdown cell listing what looked odd. Keep it factual, and leave out explanations until you have evidence.
### First-look notes
- 10,000 rows, 7 columns, as expected from the export log.
- `amount` has 212 missing values; minimum is -40.
- `region` is `object`; casing looks inconsistent in `head()`.
- Mean `amount` is well above the median.
- **Next step:** audit missing values, duplicates, and negative amounts.This list becomes the checklist for the next section. It also gives a reader the reason behind each cleaning rule later.
Common errors
- Describing and then cleaning in the same cell. You lose the record of the original state. Keep the first look on
df_raw. - Trusting
head()alone. The first five rows are a tiny, often unrepresentative slice. - Skipping dtype review because
describe()looks fine.describe()omitsobjectcolumns by default, so a numeric column stored as text silently disappears from it. If a column you expect is missing from the defaultdescribe()output, check its dtype. - Forgetting that
info()returnsNone. Assigning its result to a variable gives you nothing useful. - Reading statistics without the count. Always check how many values stand behind each number.
Exercise
After loading a file, df.info() shows quantity as float64 with 9,800 non-null values out of 10,000 rows, and describe() shows a minimum of 1 and a maximum of 12. What two conclusions can you draw, and what is your next step?
Show answer
The column has 200 missing values (10,000 minus 9,800), and that missing data is the likely reason it is stored as float64 instead of int64, because NaN is a float. The values themselves look plausible (1 to 12). The next step is to record both facts in the first-look notes and examine the missing rows in the data quality audit, for example by checking whether they cluster in particular regions or dates.
Exercise
A column price appears in df.info() as object, and it does not appear in the output of df.describe(). Why, and how would you find the offending values?
Show answer
describe() with default arguments only summarizes numeric columns, so a column stored as text is left out. At least one value is not a clean number, such as "N/A" or "$1,200". Find it with pd.to_numeric(df["price"], errors="coerce"), then select rows where the result is NaN but the original value is not null, for example df[pd.to_numeric(df["price"], errors="coerce").isna() & df["price"].notna()].