Data preparation takes most of the time because real-world data is messy and needs cleaning before it can be used. This step makes sure the machine learning model learns from good, useful information.
Why data preparation consumes most ML time in ML Python
No fixed code syntax because data preparation involves many steps like cleaning, transforming, and selecting data.Data preparation is not a single command but a set of tasks done before training.
Common tools include pandas for cleaning and sklearn for transforming data.
import pandas as pd df = pd.read_csv('data.csv') df = df.dropna() # Remove rows with missing values
from sklearn.preprocessing import StandardScaler scaler = StandardScaler() data_scaled = scaler.fit_transform(data)
df['category'] = df['category'].astype('category').cat.codes
This example shows cleaning missing data, converting categories, training a simple model, and checking accuracy.
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score # Sample data with missing values and categories data = {'age': [25, 30, None, 22, 40], 'income': [50000, 60000, 55000, None, 65000], 'gender': ['M', 'F', 'F', 'M', 'F'], 'purchased': [0, 1, 0, 1, 1]} df = pd.DataFrame(data) # Data preparation # 1. Remove rows with missing values clean_df = df.dropna() # 2. Convert gender to numeric clean_df['gender'] = clean_df['gender'].astype('category').cat.codes # 3. Split features and target X = clean_df[['age', 'income', 'gender']] y = clean_df['purchased'] # 4. Split into train and test X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=42) # 5. Train model model = LogisticRegression() model.fit(X_train, y_train) # 6. Predict and evaluate predictions = model.predict(X_test) accuracy = accuracy_score(y_test, predictions) print(f"Predictions: {predictions}") print(f"Accuracy: {accuracy:.2f}")
Data preparation often takes 70-80% of the total project time.
Good data preparation improves model accuracy and reliability.
Skipping data cleaning can cause wrong or poor model results.
Data preparation cleans and organizes raw data for machine learning.
This step takes most time because real data is often messy and incomplete.
Proper preparation leads to better and more trustworthy models.
Practice
Solution
Step 1: Understand the nature of raw data
Raw data collected from real sources often contains errors, missing values, and inconsistencies.Step 2: Recognize the need for cleaning and organizing
Before training, data must be cleaned and formatted properly to ensure the model learns correctly.Final Answer:
Because raw data is often messy and needs cleaning before use -> Option CQuick Check:
Messy data = More preparation time [OK]
- Confusing model training time with data cleaning time
- Thinking deployment takes the most time
- Assuming testing is the longest step
df?Solution
Step 1: Recall pandas method for missing values
The methodisnull()returns a DataFrame of booleans indicating missing values.Step 2: Summing missing values per column
Usingsum()on the boolean DataFrame counts missing values per column.Final Answer:
df.isnull().sum() -> Option AQuick Check:
pandas isnull + sum = count missing [OK]
- Using non-existent pandas methods
- Confusing isnull() with isna() (both work but only isnull() shown)
- Trying to call methods that don't exist on DataFrame
import pandas as pd
data = {'age': [25, None, 30], 'salary': [50000, 60000, None]}
df = pd.DataFrame(data)
df_filled = df.fillna(df.mean())
print(df_filled)
What will be the output?Solution
Step 1: Understand df.mean()
Calculates mean of each numeric column ignoring null (NaN) values.Step 2: fillna with means
fillna replaces missing values with the corresponding column mean.Final Answer:
DataFrame with missing values replaced by column means -> Option DQuick Check:
fillna(df.mean()) fills missing with mean [OK]
- Thinking fillna(df.mean()) causes error
- Assuming missing values remain unchanged
- Believing missing values become zero
import pandas as pd
data = {'height': [170, None, 160], 'weight': [70, 65, None]}
df = pd.DataFrame(data)
df_clean = df.dropna(axis=1)
print(df_clean)
What is wrong with this code if the goal is to remove rows with missing data?Solution
Step 1: Understand dropna axis parameter
axis=0 drops rows; axis=1 drops columns with missing values.Step 2: Identify the mistake
Using axis=1 removes columns, but the goal is to remove rows.Final Answer:
dropna(axis=1) removes columns, not rows -> Option BQuick Check:
axis=1 means columns, not rows [OK]
- Confusing axis=1 with rows
- Thinking dropna always removes rows by default
- Believing dropna needs threshold parameter
Solution
Step 1: Consider filling missing values
Replacing missing data with mean keeps data size and reduces bias from dropping rows.Step 2: Standardize text format
Converting text to lowercase fixes inconsistencies and helps model learn better.Final Answer:
Filling missing values with mean and converting all text to lowercase -> Option AQuick Check:
Fill missing + text clean = better data [OK]
- Dropping all rows loses too much data
- Ignoring missing values causes errors
- Shuffling or dropping duplicates alone won't fix missing data
Ready to prove it?
Pass the test and this pattern moves unknown
