pandas and NumPy 3 cheatsheet
pandas and NumPy 3: Cleaning and transforming
11 common pandas and NumPy 3 tasks.
Drop rows with missing values
Remove rows that have a missing value in the given columns.
df = df.dropna(subset=["email"])
Fill missing values
Replace missing values in a column with a default.
df["age"] = df["age"].fillna(df["age"].median())
Add a column
Create a column from others. Vectorized operations are much faster than apply.
df = df.assign(total=df["price"] * df["qty"])
Add a column based on a condition
Choose one of two values per row.
df["group"] = np.where(df["age"] >= 18, "adult", "minor")
Clean text columns
Apply string methods to a whole column.
df["email"] = df["email"].str.strip().str.lower()
Parse dates
Convert text to datetimes, then pull out parts.
df["date"] = pd.to_datetime(df["date"])
df["month"] = df["date"].dt.month