Project: Clean the Data
Cleaning means checking for gaps and copies, then fixing the types. The sales table is small, so every check is quick.
Check for gaps
isna counts the gaps in each column. Every count here is zero.
import io
import pandas as pd
SALES_CSV = """
order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""
sales = pd.read_csv(io.StringIO(SALES_CSV))
print(sales.isna().sum())
Fill a gap
One frame has a gap in units. fillna puts 0 in its place.
import pandas as pd
df = pd.DataFrame({"product": ["Tea", "Coffee"], "units": [2, None]})
df = df.fillna({"units": 0})
print(df)
Drop a copied row
One row appears twice. drop_duplicates keeps the first copy only.
import pandas as pd
df = pd.DataFrame({"product": ["Tea", "Tea", "Mug"], "units": [2, 2, 3]})
print(df.duplicated().sum())
df = df.drop_duplicates()
print(df)
Fix a type
Units arrive as text here. astype turns them into whole numbers.
import pandas as pd
df = pd.DataFrame({"units": ["2", "1", "3"]})
df["units"] = df["units"].astype("int64")
print(df.dtypes)
Example
import io
import pandas as pd
SALES_CSV = """
order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""
sales = pd.read_csv(io.StringIO(SALES_CSV))
sales = sales.fillna({"units": 0})
sales = sales.drop_duplicates()
sales["date"] = pd.to_datetime(sales["date"])
print(sales.dtypes)
print(sales.shape)
Key points
- Use isna to find missing values in a column.
- Use fillna to fill a gap with a chosen value.
- Use duplicated to find copied rows.
- Use drop_duplicates to keep only the first copy of each row.
- Use astype to change a column to a new type.
In this example, the sales table loads from its CSV text. fillna fills any gaps, and drop_duplicates removes copied rows. to_datetime turns the date column into real dates. dtypes prints the new types, and shape confirms twelve rows and seven columns.
Note
drop_duplicates keeps the first copy. The later copies go away.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Which call fills missing values with 0?