Useful Python One Liners for Data Cleaning
These one-liners are for anyone who spends too much time wrestling messy datasets in Python — analysts, data scientists, students, and automation enthusiasts. Keep them handy for quick fixes in Jupyter notebooks, scripts, or whenever you need to tidy data without writing a full function.
Quick Wins for Messy Strings
Clean up text columns with these compact string operations that handle whitespace, case, and symbols.
- Strip all leading and trailing spaces from every string in a column:
df['col'] = df['col'].str.strip() - Replace multiple spaces with a single space:
df['col'] = df['col'].str.replace(r'\s+', ' ', regex=True) - Convert all text to lowercase for consistent matching:
df['col'] = df['col'].str.lower() - Remove every non-alphanumeric character except spaces:
df['col'] = df['col'].str.replace(r'[^\w\s]', '', regex=True) - Turn a column of mixed-case names into title case:
df['name'] = df['name'].str.title() - Remove all digits from a text column:
df['col'] = df['col'].str.replace(r'\d+', '', regex=True) - Replace missing values in a string column with 'Unknown':
df['col'] = df['col'].fillna('Unknown') - Extract the first three characters from each string:
df['prefix'] = df['col'].str[:3] - Split a column into two by the first comma:
df[['a','b']] = df['col'].str.split(',', n=1, expand=True) - Remove all line breaks from text:
df['col'] = df['col'].str.replace(r'\n', ' ', regex=True)
Handling Missing Data Like a Pro
These one-liners help you spot, count, and fill gaps in your dataset without writing loops.
- Count missing values per column:
df.isnull().sum() - Drop rows with any missing value:
df.dropna(inplace=True) - Fill all missing numeric values with the column mean:
df = df.fillna(df.mean()) - Fill missing values with the previous row's value (forward fill):
df = df.fillna(method='ffill') - Fill missing values with the next row's value (backward fill):
df = df.fillna(method='bfill') - Replace a specific placeholder like 'N/A' with NaN:
df.replace('N/A', pd.NA, inplace=True) - Keep only rows that have at least two non-null values:
df = df.dropna(thresh=2) - Fill missing values in one column with the median of that column:
df['col'] = df['col'].fillna(df['col'].median()) - Interpolate missing values linearly for time series:
df = df.interpolate() - Show columns with the most missing values first:
df.isnull().sum().sort_values(ascending=False)
Fixing Data Types and Formats
Convert columns to the right type and standardise formats with these one-liners.
- Convert a column to datetime with automatic parsing:
df['date'] = pd.to_datetime(df['date']) - Convert a column to numeric, coercing errors to NaN:
df['num'] = pd.to_numeric(df['num'], errors='coerce') - Change all column names to lowercase:
df.columns = [c.lower() for c in df.columns] - Rename a single column:
df.rename(columns={'old':'new'}, inplace=True) - Convert a column of strings to category type for efficiency:
df['cat'] = df['cat'].astype('category') - Strip timezone info from a datetime column:
df['date'] = df['date'].dt.tz_localize(None) - Extract the year from a datetime column:
df['year'] = df['date'].dt.year - Convert a boolean column to 0/1 integers:
df['flag'] = df['flag'].astype(int) - Format all floats to two decimal places:
df = df.round(2) - Convert a column of strings to float after removing currency symbols:
df['price'] = df['price'].str.replace('$','').astype(float)
Removing Duplicates and Filtering Rows
Keep your dataset clean by dropping duplicates and filtering out unwanted rows with these one-liners.
- Drop duplicate rows based on all columns:
df.drop_duplicates(inplace=True) - Drop duplicates based on a single column, keeping the first:
df.drop_duplicates(subset='email', keep='first', inplace=True) - Drop duplicates and keep the last occurrence:
df.drop_duplicates(keep='last', inplace=True) - Filter rows where a column value is in a list:
df = df[df['status'].isin(['active','pending'])] - Filter rows where a column is not null:
df = df[df['col'].notnull()] - Filter rows where a numeric column is above a threshold:
df = df[df['sales'] > 100] - Filter rows that contain a specific substring in a column:
df = df[df['col'].str.contains('error', case=False)] - Remove rows where a column is empty string:
df = df[df['col'] != ''] - Sample a random fraction of rows:
df = df.sample(frac=0.5, random_state=42) - Keep only the first 100 rows:
df = df.head(100)
Reshaping and Combining Data
Melt, pivot, merge, and concatenate data with these compact one-liners.
- Melt wide data into long format:
df_melted = pd.melt(df, id_vars=['id'], var_name='variable', value_name='value') - Pivot long data back to wide format:
df_pivot = df.pivot(index='id', columns='variable', values='value') - Concatenate two dataframes vertically:
df = pd.concat([df1, df2], ignore_index=True) - Merge two dataframes on a common column:
df = pd.merge(df1, df2, on='key', how='left') - Join two dataframes on the index:
df = df1.join(df2, how='inner') - Stack the last level of a MultiIndex:
df_stacked = df.stack() - Unstack a level back to columns:
df_unstacked = df.unstack() - Transpose rows and columns:
df_t = df.T - Group by a column and get the mean of all others:
df.groupby('category').mean() - Apply a function to each row:
df['new'] = df.apply(lambda row: row['a'] + row['b'], axis=1)
Short, Snappy One-Liners for Everyday Use
These are the quick ones you'll memorise first — perfect for fast data exploration and cleanup.
- Show basic info about the dataframe:
df.info() - Get summary statistics for numeric columns:
df.describe() - List all column names:
df.columns.tolist() - Count unique values in a column:
df['col'].value_counts() - Get the number of rows and columns:
df.shape - Sort by a column in descending order:
df.sort_values('col', ascending=False) - Reset the index after filtering:
df = df.reset_index(drop=True) - Rename all columns to snake_case:
df.columns = [c.lower().replace(' ', '_') for c in df.columns] - Drop a list of columns:
df.drop(columns=['a','b'], inplace=True) - Check for duplicate rows:
df.duplicated().sum()
Tips for Choosing and Personalising These One-Liners
Pick the one-liner that matches your immediate task — don’t overthink it. To make it yours, adjust column names, thresholds, or the specific string pattern to fit your data. You can also combine two or three one-liners in a pipeline for more complex cleaning. Keep a personal cheat sheet with your most-used variations.
Frequently Asked Questions
How do I remember all these one-liners?
Start with the ones you use most often and write them down. Repeating them in your own projects will make them stick.
Can I use these one-liners on large datasets?
Yes, most are vectorised and efficient, but for very large data, consider using dask or chunking.
Do these work in both Jupyter and regular scripts?
Absolutely — they are plain Python and pandas code that runs anywhere.
How do I adapt a one-liner to my specific column names?
Simply replace the placeholder column names like 'col' or 'date' with your actual column names.
What if a one-liner gives an error?
Check the data type of your column first, and make sure you've imported pandas as pd. Often the issue is a missing regex=True or a column not existing.