Lesson 30 · Python For Machine Learning
Building a Credit Card Fraud Detection System with Python and Machine Learning
Welcome! Today we will explore Python by working through a real-world problem: detecting credit card fraud. You will learn the basics of Python as we gently…
- CoursePython For Machine Learning
- Lesson30 of 16
- Video10 min
- FormatJupyter notebook · 22 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynb
Beginner Python: Credit Card Fraud Detection#
Welcome! Today we will explore Python by working through a real-world problem: detecting credit card fraud.
You will learn the basics of Python as we gently build skills toward working with actual data.
# Let us start with a simple message
print("Hello, future fraud detector!")
What is Fraud Detection?#
Fraud detection means finding suspicious activities, like fake credit card purchases.
We use data and Python to spot these problems early.
# Python ignores comments like this line when running your code.
# Now we will assign numbers to variables.
apple_count = 3
orange_count = 4
print("I have", apple_count, "apples and", orange_count, "oranges.")
# Let us use a string (text) variable.
owner_name = "Eva"
print(owner_name, "owns these fruits.")
# We can ask the user to enter their name.
your_name = input("What is your name? ")
print("Welcome,", your_name, "!")
Lists: Storing Many Values#
Lists help us store many items at once. For example, several numbers, or names.
We will use lists a lot in fraud detection.
# Here is a list of sample card transactions.
transactions = [23.5, 99.9, 120.0, 5.30, 500.00]
print("First transaction:", transactions[0])
print("Last transaction:", transactions[-1])
# Let us loop through the list and print each transaction.
for amount in transactions:
print("Transaction amount:", amount)
# Stay safe: import warning library and filter warnings.
import warnings
warnings.filterwarnings('ignore')
# Data setup: download credit card fraud data sample
import pandas as pd
url = "https://raw.githubusercontent.com/DiptarajSinha/credit-card-fraud-detection/main/sample_creditcard.csv"
df = pd.read_csv(url)
print("Data shape:", df.shape)
print("First five rows:")
print(df.head())
# Check the class balance (fraud or not fraud)
print(df['Class'].value_counts())
# Let us rename columns to keep things clear.
df = df.rename(columns={'Class': 'Fraud'})
print(df.columns)
# Check for missing data.
print(df.isna().sum())
# Select all fraud cases.
frauds = df[df['Fraud'] == 1]
print("Number of frauds:", len(frauds))
print(frauds[['Amount','Fraud']].head())
# Mark any big purchases (over 200) as suspicious.
df['Suspicious'] = df['Amount'] > 200
print(df[['Amount','Suspicious']].head(10))
# Simple rule: flag transactions over 500 as 'Alert'.
alerts = []
for amt in df['Amount']:
if amt > 500:
alerts.append('Alert')
else:
alerts.append('Safe')
df['AlertFlag'] = alerts
print(df[['Amount','AlertFlag']].head(10))
# Calculate average transaction amount for fraud and not-fraud.
avg_fraud = df[df['Fraud'] == 1]['Amount'].mean()
avg_normal = df[df['Fraud'] == 0]['Amount'].mean()
print("Average fraud amount:", round(avg_fraud,2))
print("Average normal amount:", round(avg_normal,2))
Mini-Project: Spotting Fake Transactions#
Let us try building a simple rule to find unusual transactions.
We want to see which are likely to be fake.
# Mini-project Part 1: Ask the user for a custom limit.
limit = input("What is your suspicious amount limit? ")
limit = float(limit)
df['UserAlert'] = df['Amount'] > limit
print(df[['Amount', 'UserAlert']].head(10))
# Mini-project Part 2: Review flagged transactions.
flagged = df[df['UserAlert']]
print("Total flagged by your rule:", len(flagged))
print(flagged[['Amount','UserAlert']].head())
# Best practices: always check your data before making decisions.
if df.empty:
print("No data to check!")
else:
print("Ready to analyze fraud data.")
# Troubleshooting: handle errors gently.
try:
missing_value = df.loc[10000, 'Amount']
except Exception as e:
print("Handled error:", e)
Recap#
We explored lists, variables, data tables, and simple fraud flags.
These are building blocks for deeper data science and fraud prevention.
Thank you for joining this beginner Python lesson!
If you enjoyed this, like and subscribe for more fun projects.
Now try making up your own suspicious transaction rulesand happy coding!
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



