FormulaCamp
Completed
15. Python in Excel and AI · pandas and Python Charts · 20 min

2. pandas: Cleaning Data

Lesson 2 of 6
Task 1 of 4
  1. In D2:D9, clean up the city names: no extra spaces and a capital first letter (like str.strip().str.title()).

Lesson theory

In Python in Excel, a range becomes a pandas table, a DataFrame. Typical cleanup of an export takes a few lines:

df = xl("A1:B9", headers=True)
df["City"] = df["City"].str.strip().str.title()   # trim spaces, capitalize "Austin"
df["Amount"] = pd.to_numeric(df["Amount"])        # text "1200" -> number 1200
df = df.dropna(subset=["Amount"])                 # drop rows with no amount
len(df), df["Amount"].sum(), df["Amount"].mean()
  • str.strip() is like TRIM; str.title() is like PROPER;
  • pd.to_numeric or astype(float) is like VALUE: a number stored as text becomes a number;
  • dropna() removes empty values (NaN). The functions sum() and mean() skip empties anyway, just like SUM and AVERAGE.

A good habit is to check Python's result against ordinary formulas at least once. In this lesson you'll repeat the cleanup with formulas and get the same three numbers that the last line of code returns.

Test yourself

1. What does df.dropna(subset=["Amount"]) do?
2. Which Excel function is closest to df["City"].str.strip()?
3. Why call pd.to_numeric(df["Amount"]) before summing?
fx

Enter — commit · F2 — edit · F4 — $ in a reference · Ctrl+C/Ctrl+V — copy and paste · Ctrl+Z — undo

Esc or F6 — leave the sheet for the «Check» button · Shift+Tab in the first cell — back to the page