By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
A Hyper-Practical, Zero-Fluff Study Guide
You’re building a data pipeline that processes customer transactions. Your script reads a CSV file, cleans the data, and calculates average spending. Suddenly, your code crashes with:
TypeError: unsupported operand type(s) for +: 'str' and 'float'
Why? Because the CSV parser read all values as strings ("12.99"), but your math operations expected floats (12.99). This is a data type mismatch—one of the most common (and avoidable) bugs in data science.
"12.99"
12.99
In Python for Data Science, data types, typecasting, and variables are the foundation of everything: - Data types determine what operations you can perform (e.g., you can’t multiply a string by a number).- Typecasting lets you convert between types (e.g., turning "5" into 5 for calculations).- Variables are how you store and reference data (e.g., customer_age = 30).
"5"
5
customer_age = 30
Real-world scenario:You inherit a legacy script that loads a dataset, but the "price" column is stored as strings. Your boss asks for a 10% price increase, but the script fails because "$19.99" * 1.1 is invalid. Fixing this requires understanding data types and typecasting.
"$19.99" * 1.1
If you ignore this, you’ll waste hours debugging silent failures (e.g., "5" + 3 returns "53", not 8), or worse—your model will train on garbage data (e.g., treating "N/A" as a number).
"5" + 3
"53"
8
"N/A"
int
42
-3
1.0
1
float
3.14
-0.001
0.1 + 0.2 == 0.3
False
decimal.Decimal
complex
3 + 4j
bool
True
df[df["active"] == True]
1 == True
0 == False
str
"hello"
'42'
.replace()
f-strings
f"User {id}"
list
[1, 2, 3]
numpy.array
pandas.Series
tuple
(1, 2, 3)
(lat, lon)
range
range(0, 10)
dict
{"name": "Alice", "age": 30}
{"price": "cost"}
set
{1, 2, 3}
set(df["category"])
if "fraud" in transaction_types
NoneType
x = None
is None
== None
df["column"].isna()
int("5")
str(3.14)
if value.isdigit(): int(value)
int("5.5")
x = 10
customer_age
CustomerAge
x
a = b
a
b
pandas
pip install pandas
"price"
$
Clean a dataset where: - The "price" column is stored as strings (e.g., "$19.99").- The "quantity" column has missing values (NaN).- The "date" column is a string (e.g., "2023-01-15").
"$19.99"
"quantity"
NaN
"date"
"2023-01-15"
import pandas as pd # Load the CSV (replace with your file path) df = pd.read_csv("transactions.csv") print(df.head())
Expected output:
id price quantity date 0 1 $19.99 2.0 2023-01-15 1 2 $5.00 NaN 2023-01-16 2 3 $12.50 1.0 2023-01-17
# Remove $ and convert to float df["price"] = df["price"].str.replace("$", "").astype(float) print(df["price"].head())
0 19.99 1 5.00 2 12.50 Name: price, dtype: float64
# Fill NaN with 0 (or use .fillna(1) for default quantity) df["quantity"] = df["quantity"].fillna(0).astype(int) print(df["quantity"].head())
0 2 1 0 2 1 Name: quantity, dtype: int64
# Convert string to datetime df["date"] = pd.to_datetime(df["date"]) print(df["date"].head())
0 2023-01-15 1 2023-01-16 2 2023-01-17 Name: date, dtype: datetime64[ns]
# Multiply price by quantity (now both are numeric) df["revenue"] = df["price"] * df["quantity"] print(df[["price", "quantity", "revenue"]].head())
price quantity revenue 0 19.99 2 39.98 1 5.00 0 0.00 2 12.50 1 12.50
# Check dtypes print(df.dtypes)
id int64 price float64 quantity int64 date datetime64[ns] revenue float64 dtype: object
api_key = "12345"
os.getenv("API_KEY")
isinstance(value, int)
float64
float32
category
"male"
"female"
df.copy()
int(5.0)
# price: float (e.g., 19.99)
python def calculate_revenue(price: float, quantity: int) -> float: return price * quantity
python if not isinstance(price, (int, float)): logging.warning(f"Invalid price type: {type(price)}")
sys.getsizeof()
TypeError
.astype(float)
int()
str.replace("$", "")
None
pd.isna()
def foo(x=[])
def foo(x=None): x = x or []
a = b = []
a, b = [], []
0.1 + 0.2 != 0.3
int("3.14")
ValueError
"How do you convert "5" to an integer?" → int("5") (not float("5")).
float("5")
Data type properties:
"What is the difference between == and is?" → == checks value, is checks memory address.
==
is
Pandas-specific:
pd.to_datetime(df["column"])
np.nan
astype()
to_numeric()
astype(float)
pd.to_numeric(df["column"], errors="coerce")
"You have a DataFrame with a "user_id" column stored as strings (e.g., "1001"). You need to merge it with another DataFrame where "user_id" is an integer. What’s the most efficient way to handle this?"
"user_id"
"1001"
Answer:
df1["user_id"] = df1["user_id"].astype(int) # or pd.to_numeric(df1["user_id"]) df_merged = pd.merge(df1, df2, on="user_id")
Why? Avoids type mismatches during merge and is faster than converting during the merge.
Challenge: Write a function that takes a list of mixed types ([1, "2", 3.0, "4.5", None]) and returns a new list with all values converted to floats. Skip None values.
[1, "2", 3.0, "4.5", None]
Solution:
def convert_to_floats(mixed_list): return [float(x) for x in mixed_list if x is not None] # Test print(convert_to_floats([1, "2", 3.0, "4.5", None])) # [1.0, 2.0, 3.0, 4.5]
Why it works: - float(x) handles int, str, and float inputs.- if x is not None skips None values.
float(x)
if x is not None
{"a": 1}
"5.5"
float()
float("5.5")
5.5
"$5.5"
str()
str(5)
bool()
bool(1)
0
""
[]
list()
list((1, 2))
[1, 2]
pd.to_numeric()
pd.to_numeric(["1", "2"])
errors="coerce"
df["col"] = df["col"].astype(int)
pd.to_datetime(df["date"])
df["col"] = pd.to_numeric(df["col"], downcast="float")
df["col"] = df["col"].astype("category")
df["col"].isna()
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.