BBampaa

Lessons › Python

Python lesson

Fixing data types

2680.0. Before the fix, .sum() would just join the text together instead of adding it up.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Take out the $ and the comma, then turn the text into numbers with .astype:

df["Revenue"] = df["Revenue"].str.replace("$", "").str.replace(",", "").astype(float)
df["Revenue"].sum()

Output:

2680.0

Key points

.str.replace("$", "")Take out the $ sign: replace it with nothing.
.str.replace(",", "")Then the comma: "1,200" becomes "1200".
.astype(float)Turn the text into numbers. Use .astype(int) for whole numbers.
Spot it.sum() joins text instead of adding it. That's the clue the numbers are text.

Put together: df["Revenue"].str.replace("$", "").str.replace(",", "").astype(float).

Practice

Try each one in your head first, then open the answer.

1. Build a line that turns the Revenue column into numbers.
df["Revenue"] = df["Revenue"].str.replace("$", "").str.replace(",", "").astype(float)
2. Build a line that turns the Qty column into whole numbers.
df["Qty"] = df["Qty"].astype(int)
3. Turn the Qty column into whole numbers, then show the total quantity.
df["Qty"] = df["Qty"].astype(int)
df["Qty"].sum()
4. Clean the Revenue column into numbers, then show the total revenue.
df["Revenue"] = df["Revenue"].str.replace("$", "").str.replace(",", "").astype(float)
df["Revenue"].sum()
5. The till export won't add up. Clean the Revenue column, then show the total revenue for each store.
df["Revenue"] = df["Revenue"].str.replace("$", "").str.replace(",", "").astype(float)
df.groupby("Store")["Revenue"].sum()

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed