Credit Card Fraud
This dataset consists of credit card transactions in the western United States. It includes information about each transaction including customer details, the merchant and category of purchase, and whether or not the transaction was a fraud.
Note: You can access the data via the File menu or in the Context Panel at the top right of the screen next to Report, under Files. The data dictionary and filenames can be found at the bottom of this workbook.
Source: Kaggle The data was partially cleaned and adapted by DataCamp.
We've added some guiding questions for analyzing this exciting dataset! Feel free to make this workbook yours by adding and removing cells, or editing any of the existing cells.
Explore this dataset
Here are some ideas to get your started with your analysis...
- 🗺️ Explore: What types of purchases are most likely to be instances of fraud? Consider both product category and the amount of the transaction.
 - 📊 Visualize: Use a geospatial plot to visualize the fraud rates across different states.
 - 🔎 Analyze: Are older customers significantly more likely to be victims of credit card fraud?
 
🔍 Scenario: Accurately Predict Instances of Credit Card Fraud
This scenario helps you develop an end-to-end project for your portfolio.
Background: A new credit card company has just entered the market in the western United States. The company is promoting itself as one of the safest credit cards to use. They have hired you as their data scientist in charge of identifying instances of fraud. The executive who hired you has have provided you with data on credit card transactions, including whether or not each transaction was fraudulent.
Objective: The executive wants to know how accurately you can predict fraud using this data. She has stressed that the model should err on the side of caution: it is not a big problem to flag transactions as fraudulent when they aren't just to be safe. In your report, you will need to describe how well your model functions and how it adheres to these criteria.
You will need to prepare a report that is accessible to a broad audience. It will need to outline your motivation, analysis steps, findings, and conclusions.
Data Dictionary
| transdatetrans_time | Transaction DateTime | 
|---|---|
| merchant | Merchant Name | 
| category | Category of Merchant | 
| amt | Amount of Transaction | 
| city | City of Credit Card Holder | 
| state | State of Credit Card Holder | 
| lat | Latitude Location of Purchase | 
| long | Longitude Location of Purchase | 
| city_pop | Credit Card Holder's City Population | 
| job | Job of Credit Card Holder | 
| dob | Date of Birth of Credit Card Holder | 
| trans_num | Transaction Number | 
| merch_lat | Latitude Location of Merchant | 
| merch_long | Longitude Location of Merchant | 
| is_fraud | Whether Transaction is Fraud (1) or Not (0) | 
You can query the pre-loaded CSV file using SQL directly. Here’s a sample query, followed by some sample Python code and outputs:
SELECT * FROM 'credit_card_fraud.csv'
LIMIT 10import pandas as pd 
import duckdb
ccf = pd.read_csv('credit_card_fraud.csv') 
ccf.head(100)SELECT 
  COUNT(*) AS total,
  SUM(CASE WHEN is_fraud = 1 THEN 1 ELSE 0 END) AS fraud_count,
  ROUND(100 * SUM(CASE WHEN is_fraud = 1 THEN 1 ELSE 0 END) / COUNT(*), 2) AS fraud_rate_pct
FROM ccf;
🗺️ Explore: What types of purchases are most likely to be instances of fraud? Consider both product category and the amount of the transaction.
SELECT  category,
        SUM(is_fraud) AS total_fraud,
		COUNT(*) total_trasactions,
        ROUND(SUM(amt), 2) AS total_amount,
        ROUND(100.0 * SUM(is_fraud) / COUNT(*),2) AS fraud_perc
FROM ccf
GROUP BY category
ORDER BY fraud_perc DESC;import duckdb
query = """
SELECT  
  category,
  SUM(is_fraud) AS total_fraud,
  COUNT(*) AS total_transactions,
  ROUND(SUM(amt), 2) AS total_amount,
  ROUND(100.0 * SUM(is_fraud) / COUNT(*),2) AS fraud_perc
FROM ccf
GROUP BY category
ORDER BY total_fraud DESC
"""
df_category = duckdb.query(query).to_df()
df_category.head()import matplotlib.pyplot as plt
# Sort categories by total amount
df_category = df_category.sort_values(by='total_amount', ascending=False)
# Extract data
categories = df_category['category']
amounts = df_category['total_amount']
fraud_rates = df_category['fraud_perc']
transaction_counts = df_category['total_transactions']
# Create the plot
fig, ax1 = plt.subplots(figsize=(12, 6))
# Bar chart for total amount
bar_color = 'skyblue'
bars = ax1.bar(categories, amounts, color=bar_color)
ax1.set_ylabel('Total Transaction Amount ($)', color=bar_color)
ax1.set_xlabel('Purchase Category')
ax1.tick_params(axis='y', labelcolor=bar_color)
ax1.set_xticklabels(categories, rotation=45, ha='right')
# Line chart for fraud percentage
ax2 = ax1.twinx()
line_color = 'crimson'
ax2.plot(categories, fraud_rates, color=line_color, marker='o')
ax2.set_ylabel('Fraud Percentage (%)', color=line_color)
ax2.tick_params(axis='y', labelcolor=line_color)
plt.title("Fraud Analysis by Category: Amount and Rate")
plt.tight_layout()
plt.show()