Lesson 5 of 6 · about 20 minutes
Data types and missing values
Data types
Every column has a dtype: the kind of values it holds. pandas picks one when it builds the table, and it decides what you can do with the column. dtypes shows them all:
import pandas as pd
df = pd.DataFrame({
"name": ["Ava", "Ben", "Cleo"],
"age": [12, 13, 12],
"height": [1.52, 1.61, 1.49],
"member": [True, False, True],
})
print(df.dtypes)The output:
name object
age int64
height float64
member bool
dtype: objectThe common ones are int64 (whole numbers), float64 (decimal numbers), bool (True or False) and object, which pandas uses for text. A single column's type is df["age"].dtype.
Changing a type
Data from files often has the wrong type. Numbers stored as text cannot be added up. astype() converts a column:
import pandas as pd
df = pd.DataFrame({"item": ["pen", "book", "bag"], "price": ["2", "12", "25"]})
print(df["price"].sum())
df["price"] = df["price"].astype(int)
print(df["price"].sum())
print(df["price"].dtype)The output:
21225
39
int64Before the conversion, sum() glued the strings together into "21225". After it, the numbers are added properly. For text that might not be a valid number, pd.to_numeric(df["price"], errors="coerce") turns anything it cannot read into a missing value instead of stopping with an error.
Quick check
A column holds "10", "20" and "30" as text. What does astype(int) followed by sum() give?
Missing values
Real data has gaps: a question someone skipped, a sensor that failed. pandas marks a missing value as NaN ("not a number"):
import pandas as pd
import numpy as np
df = pd.DataFrame({
"name": ["Ava", "Ben", "Cleo", "Dan"],
"age": [12, np.nan, 12, 14],
"city": ["Leeds", "York", None, "Bath"],
})
print(df)
print()
print(df.isnull().sum())The output:
name age city
0 Ava 12.0 Leeds
1 Ben NaN York
2 Cleo 12.0 None
3 Dan 14.0 Bath
name 0
age 1
city 1
dtype: int64isnull() gives True wherever a value is missing, and .sum() counts the Trues in each column. notnull() is the opposite. Note that the age column became float64: NaN is a decimal value, so a whole-number column with a gap is stored as decimals.
To see the rows with a missing age:
import pandas as pd
import numpy as np
df = pd.DataFrame({"name": ["Ava", "Ben", "Cleo"], "age": [12, np.nan, 13]})
print(df.loc[df["age"].isnull()])The output:
name age
1 Ben NaNQuick check
Which line counts the missing values in each column?
Filling and dropping
You have two choices: fill the gaps or drop the rows that have them.
import pandas as pd
import numpy as np
df = pd.DataFrame({
"name": ["Ava", "Ben", "Cleo", "Dan"],
"age": [12, np.nan, 12, 14],
"city": ["Leeds", "York", None, "Bath"],
})
print(df.fillna({"age": df["age"].mean(), "city": "Unknown"}))
print()
print(df.dropna())The output:
name age city
0 Ava 12.000000 Leeds
1 Ben 12.666667 York
2 Cleo 12.000000 Unknown
3 Dan 14.000000 Bath
name age city
0 Ava 12.0 Leeds
3 Dan 14.0 Bathfillna() puts a value in every gap, and with a dictionary you choose a different value for each column (here the average age and the word Unknown). dropna() removes every row that has any missing value.
Replacing values
replace() swaps one value for another anywhere in a column, which is handy for fixing spelling or codes:
import pandas as pd
cities = pd.Series(["Leeds", "leeds", "York", "N/A"])
print(cities.replace({"leeds": "Leeds", "N/A": "Unknown"}))The output:
0 Leeds
1 Leeds
2 York
3 Unknown
dtype: objectExercise 1: Numbers stored as text
The visitors column holds text. Convert it to whole numbers (int) and then print the total number of visitors.
Exercise 2: Count the gaps
Store the number of missing values in each column in a Series called missing and print it.
Exercise 3: Fill the gaps
Make a DataFrame called clean from df where missing rating values are filled with 0 and missing genre values with unknown.
Lesson 5 complete
You finished data types and missing values and passed every exercise.
What you learned
df.dtypesanddf["col"].dtypeshow the types:int64,float64,bool,object(text).astype(int),astype(float)andastype(str)convert a column;pd.to_numeric(..., errors="coerce")is the safe way for messy text.- Missing values are NaN.
isnull().sum()counts them per column. fillna(value)fills gaps,dropna()removes rows with gaps.replace({old: new})swaps values.