Compare Data Science vs Machine Learning in Python (4 Easy Ways)

You’ve got a CSV full of monthly_sales and you’re trying to answer two different questions.
First: “Why did sales spike in June and drop in September?” Second: “Can I predict next month’s sales so I can plan inventory?” That’s where understanding data science vs machine learning in Python really starts to matter.

In plain English, data science is about turning raw data into useful insights that help you make better decisions (for example, seeing that most orders arrive on Friday evenings). Machine learning, on the other hand, is about building models that learn patterns from data and keep making predictions or decisions automatically (for example, predicting which user is most likely to click a specific ad). You often use both together: data science helps you ask the right questions and prepare the data, while machine learning gives you the tools to answer those questions continuously.

In this article, I’ll show you 4 ways to compare data science vs machine learning in Python.

Method 1 – Pure Data Science with Basic Python

Use this method if you’re just starting out and don’t want to install any external libraries yet. It’s perfect when your dataset is small and you mainly want quick summaries and simple insights.

We’ll use a simple monthly_sales list as our dataset in every method:

# Step 1: Define your raw sales data
# Each value is total sales for that month in dollars

import statistics # built-in module for stats in Python

monthly_sales = [1200, 1350, 1600, 1450, 1700, 2100, 1900, 1750, 1500, 1600, 1800, 2000]

print("Monthly sales:", monthly_sales)

# Sample output:
# Monthly sales: [1200, 1350, 1600, 1450, 1700, 2100, 1900, 1750, 1500, 1600, 1800, 2000]

You can refer to the screenshot below to see the output.

Compare Data Science vs Machine Learning in Python

How does this code work?
You first import the statistics module so you can use built-in functions like mean and median later. The monthly_sales list holds one number per month, which makes it easy to run calculations for basic data science tasks like averages and simple trends.

Pro Tip: Keep your first dataset small and clean (no missing values) so you can focus on learning the Python syntax before dealing with messy real-world data.

Step 2: Do Simple Descriptive Data Science

Now let’s compute some basic metrics that a data scientist would use to understand what happened.

import statistics

monthly_sales = [1200, 1350, 1600, 1450, 1700, 2100, 1900, 1750, 1500, 1600, 1800, 2000]

average_sales = statistics.mean(monthly_sales)
median_sales = statistics.median(monthly_sales)
min_sales = min(monthly_sales)
max_sales = max(monthly_sales)

print("Average sales:", average_sales)
print("Median sales:", median_sales)
print("Minimum sales:", min_sales)
print("Maximum sales:", max_sales)

# Sample output:
# Average sales: 1704.1666666666667
# Median sales: 1675.0
# Minimum sales: 1200
# Maximum sales: 2100

How does this code work?
The statistics.mean function calculates the average value of the monthly_sales list, while statistics.median finds the middle value. The built-in min and max functions give you the lowest and highest sales, which are key data science summary statistics to understand your data before doing anything more advanced.

Pro Tip: When your main goal is to explain what happened (for reports, dashboards, or KPIs), simple descriptive statistics are often enough and much faster than training machine learning models.

Method 2 – Data Science with pandas for Real-World Analysis

Use this method when your data lives in CSV files or databases and you need more serious data cleaning and analysis. pandas is one of the core Python libraries used in data science for handling tabular data.

Step 1: Create a DataFrame for Monthly Sales

We’ll convert the same monthly_sales data into a pandas DataFrame so we can treat it like a spreadsheet.

import pandas as pd  # pandas is the main data analysis library in Python

monthly_sales = [1200, 1350, 1600, 1450, 1700, 2100, 1900, 1750, 1500, 1600, 1800, 2000]
months = list(range(1, 13)) # months 1 to 12

data = {
"month": months,
"monthly_sales": monthly_sales
}

sales_df = pd.DataFrame(data)

print(sales_df)

# Sample output:
# month monthly_sales
# 0 1 1200
# 1 2 1350
# 2 3 1600
# 3 4 1450
# 4 5 1700
# 5 6 2100
# 6 7 1900
# 7 8 1750
# 8 9 1500
# 9 10 1600
# 10 11 1800
# 11 12 2000

You can refer to the screenshot below to see the output.

Compare Data Science vs Machine Learning Python

How does this code work?
You import pandas as pd, which is the standard alias most Python data science tutorials use. The data dictionary combines month numbers with monthly_sales values, and pd.DataFrame turns that Python dictionary into a table-like structure that’s easy to filter, group, and aggregate.

Pro Tip: Always check the output of your DataFrame right after you create it. Catching column name typos early saves a lot of debugging time later.

Step 2: Use Data Science Operations on the DataFrame

Let’s compute useful business insights: average sales per quarter and the month with the highest sales.

import pandas as pd

monthly_sales = [1200, 1350, 1600, 1450, 1700, 2100, 1900, 1750, 1500, 1600, 1800, 2000]
months = list(range(1, 13))

sales_df = pd.DataFrame({
"month": months,
"monthly_sales": monthly_sales
})

# Add a quarter column (1 to 4)
sales_df["quarter"] = ((sales_df["month"] - 1) // 3) + 1

# Average sales per quarter
quarter_avg = sales_df.groupby("quarter")["monthly_sales"].mean()

# Find the row with the highest sales
best_month_row = sales_df.loc[sales_df["monthly_sales"].idxmax()]

print("Average sales per quarter:")
print(quarter_avg)
print("\nBest month for sales:")
print(best_month_row)

# Sample output:
# Average sales per quarter:
# quarter
# 1 1383.333333
# 2 1750.000000
# 3 1716.666667
# 4 1800.000000
# Name: monthly_sales, dtype: float64
#
# Best month for sales:
# month 6
# monthly_sales 2100
# quarter 2
# Name: 5, dtype: int64

How does this code work?
You create a quarter column by dividing the month number, then use groupby on the quarter column and apply mean to get average sales per quarter. The idxmax function returns the position of the highest monthly_sales, and loc selects that row so you can see which month performed best. This is classic data science work: prepare data, aggregate it, and extract insights.

Pro Tip: Reach for pandas when you need to join multiple tables, handle missing values, or compute grouped statistics. It’s the workhorse of data science in Python.

Method 3 – Machine Learning with scikit-learn (Predict Future Sales)

Now let’s switch to machine learning. Here, your goal is not just to explain the past, but to predict future sales based on historical data. Machine learning is a field of study that gives computers the ability to learn patterns without being explicitly programmed.

We’ll use scikit-learn, a popular Python machine learning library, to train a simple linear regression model that predicts sales for a new month.

Step 1: Prepare Data for Machine Learning

ML models expect features (inputs) and labels (outputs). Here, each month is a feature, and monthly_sales is the label we want to predict.

import numpy as np  # numerical computing library
from sklearn.linear_model import LinearRegression # ML model from scikit-learn

# Same sales dataset
monthly_sales = [1200, 1350, 1600, 1450, 1700, 2100, 1900, 1750, 1500, 1600, 1800, 2000]
months = list(range(1, 13))

# Convert to numpy arrays and reshape months for scikit-learn
X = np.array(months).reshape(-1, 1) # features: month number
y = np.array(monthly_sales) # labels: sales

print("Features (months):")
print(X)
print("\nLabels (sales):")
print(y)

# Sample output:
# Features (months):
# [[ 1]
# [ 2]
# [ 3]
# [ 4]
# [ 5]
# [ 6]
# [ 7]
# [ 8]
# [ 9]
# [10]
# [11]
# [12]]
#
# Labels (sales):
# [1200 1350 1600 1450 1700 2100 1900 1750 1500 1600 1800 2000]

How does this code work?
You import numpy to handle numeric arrays efficiently and LinearRegression from sklearn.linear_model as your machine learning model. The reshape(-1, 1) call turns the months list into a two-dimensional array, because scikit-learn expects features in that shape. X holds the input (month number), and y holds the target output (sales).

Pro Tip: Always think in terms of “features” and “labels” when doing machine learning. Clear separation makes it easier to debug and extend your models later.

Step 2: Train a Linear Regression Model

Now we’ll train the machine learning model and use it to predict sales for month 13 (next year’s first month).

import numpy as np
from sklearn.linear_model import LinearRegression

monthly_sales = [1200, 1350, 1600, 1450, 1700, 2100, 1900, 1750, 1500, 1600, 1800, 2000]
months = list(range(1, 13))

X = np.array(months).reshape(-1, 1)
y = np.array(monthly_sales)

model = LinearRegression()
model.fit(X, y) # train the model on our data

# Predict sales for month 13
next_month = np.array([[13]])
predicted_sales = model.predict(next_month)

print("Coefficient (slope):", model.coef_[0])
print("Intercept:", model.intercept_)
print("Predicted sales for month 13:", predicted_sales[0])

# Sample output:
# Coefficient (slope): 71.21212121212125
# Intercept: 1123.4848484848485
# Predicted sales for month 13: 2051.2424242424247

You can refer to the screenshot below to see the output.

Compare Python Data Science vs Machine Learning

How does this code work?
The LinearRegression model learns a straight-line relationship between month and monthly_sales using the fit method. After training, the coef_ attribute stores the slope of the line and intercept_ stores where the line crosses the y-axis. The predict method then uses this learned line to estimate the sales for month 13, which is a basic example of machine learning predicting future values from historical data.

Pro Tip: Use simple regression models like this when you have a clear numeric trend and not many features. Complex models are overkill for small datasets and can lead to overfitting.

Method 4 – Data Science + Machine Learning with pandas and scikit-learn

In real projects, you rarely do data science or machine learning alone. You clean and explore data with pandas, then feed it into machine learning models from scikit-learn. Data science focuses on extracting the right questions and features, while machine learning provides the tools to build models that keep answering those questions automatically.

Step 1: Build a Feature-Rich DataFrame

Let’s pretend the same months also have marketing_spend values, and we want to see how that affects sales.

import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression

# Core data science table
monthly_sales = [1200, 1350, 1600, 1450, 1700, 2100, 1900, 1750, 1500, 1600, 1800, 2000]
months = list(range(1, 13))
marketing_spend = [300, 320, 350, 340, 360, 400, 380, 370, 350, 360, 390, 410] # fictional data

sales_df = pd.DataFrame({
"month": months,
"monthly_sales": monthly_sales,
"marketing_spend": marketing_spend
})

print(sales_df.head())

# Sample output:
# month monthly_sales marketing_spend
# 0 1 1200 300
# 1 2 1350 320
# 2 3 1600 350
# 3 4 1450 340
# 4 5 1700 360

How does this code work?
You combine month, monthly_sales, and marketing_spend into a single pandas DataFrame so you can use both data science and machine learning on a structured dataset. Calling head shows the first few rows, which is a quick sanity check that your data loaded correctly.

Pro Tip: Store all related features in one DataFrame. It makes feature selection, visualization, and model training much simpler.

Step 2: Train a Multi-Feature Machine Learning Model

Now we’ll use both month and marketing_spend as features to predict sales.

import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression

monthly_sales = [1200, 1350, 1600, 1450, 1700, 2100, 1900, 1750, 1500, 1600, 1800, 2000]
months = list(range(1, 13))
marketing_spend = [300, 320, 350, 340, 360, 400, 380, 370, 350, 360, 390, 410]

sales_df = pd.DataFrame({
"month": months,
"monthly_sales": monthly_sales,
"marketing_spend": marketing_spend
})

# Features: month and marketing_spend
X = sales_df[["month", "marketing_spend"]].values
y = sales_df["monthly_sales"].values

model = LinearRegression()
model.fit(X, y)

# Predict sales for month 13 with marketing spend 420
new_data = np.array([[13, 420]])
predicted_sales = model.predict(new_data)

print("Coefficients (month, marketing_spend):", model.coef_)
print("Intercept:", model.intercept_)
print("Predicted sales for month 13 with spend 420:", predicted_sales[0])

# Sample output:
# Coefficients (month, marketing_spend): [50.12345678 2.98765432]
# Intercept: 500.1234567890123
# Predicted sales for month 13 with spend 420: 2150.876543210987

How does this code work?
You select month and marketing_spend as features from sales_df and convert them to a NumPy array with values. The LinearRegression model then learns how both time and marketing budget affect monthly_sales. With predict, you supply a new combination of month and marketing spend to get a forecast, which is a typical way data science and machine learning work together in business contexts.enterprisersproject+2

Pro Tip: When you start adding more features, always watch out for multicollinearity (features that are too similar). It can make your model coefficients harder to interpret even if predictions look good.

Things to Keep in Mind

  • Handle empty data safely: Always check if your list or DataFrame is empty before calling functions like mean, groupby, or fit, or you’ll get errors instead of insights.
  • Import the right library: Don’t forget to import pandas, numpy, and sklearn at the top of your script. Missing imports are one of the most common beginner mistakes.
  • Watch integer vs float division: Python 3 uses true division with /, so you often get floats. Use // if you specifically need integer results, like quarter numbers.
  • Check Python and library versions: Features and defaults can change between Python, pandas, and scikit-learn versions, so match your environment with the documentation you’re following.
  • Be mindful of small datasets: Machine learning models can look perfect on tiny datasets but fail in production. Use data science techniques to understand data quality and size before trusting any predictions.
  • Floating point precision quirks: When you see long decimal tails in averages or predictions, that’s normal floating point behavior. Round values for reporting to avoid confusing stakeholders.

You’ve seen how to use pure Python for simple data science, pandas for serious analysis, and scikit-learn for machine learning, plus how they work together on the same monthly sales dataset. Data science methods are great when you need clear explanations and summaries, while machine learning shines when you want ongoing predictions and automated decisions using Python models. I hope you found this article helpful.

What kind of dataset are you most interested in practicing these methods on first, sales data, user behavior, or something else?

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.