The user wants a Python script to generate synthetic datasets for testing.
This is a broad request. I need to determine what kind of synthetic datasets are most useful.
Common use cases include:
Tabular Data (Structured): CSV files with columns like ID, Name, Age, Salary, Date, etc. (Good for SQL, Excel, Pandas testing).
Time Series Data: Data points indexed by time (Good for forecasting, financial apps).
Classification Data: Clusters of points (Good for ML models).
To make the script robust and useful, I should probably create a modular approach or a class-based structure that allows the user to easily configure the output.
Key features the script should have:
Ability to specify the schema (column names and types).
Support for common data types: Integers, Floats, Strings (names, emails, addresses), Dates, Booleans, Categorical.
Ability to save to a common format (CSV is the standard, maybe JSON too).
A Command Line Interface (CLI) or a simple function call interface. A CLI is more "script-like".
Library choice:
pandas: Essential for data manipulation.
numpy: Essential for random number generation.
faker: This is the gold standard for generating realistic fake names, addresses, etc. Without it, you just get random strings like "sdkjfh". With it, you get "John Doe".
Generator Class: Create a class SyntheticDataGenerator.
Methods:
_generate_integer()
_generate_float()
_generate_name()
_generate_date()
generate_row()
generate_dataset(num_rows)
Schema Definition: How will the user define columns? A dictionary seems best. E.g., {'age': 'int', 'name': 'name', 'salary': 'float'}.
Main Execution: Use argparse to let users run it from the terminal like python generate_data.py --rows 100 --output data.csv.
Refining the Plan:
Instead of a hardcoded schema inside the script, it's better to show how to customize it within the Python code, but provide a default configuration for a quick run.
I will implement a version using pandas and faker.
Drafting the code structure:
python
import pandas as pd
import numpy as np
from faker import Faker
import random
def generate_data(rows=100):
fake = Faker()
data = []
for _ in range(rows):
# manual column creation
pass
return pd.DataFrame(data)
Enhancement:
To make it more flexible, I'll create a function that takes a schema config.
Let's create a script that handles:
Basic Types: ID, Name, Email, Age, Date, Boolean.
Output: CSV.
I should also include a section on how to install the dependencies (pip install pandas numpy faker).
Code Walkthrough:
Initialize Faker.
Loop n times.
Inside loop, build a dictionary for the row.
Append to list.
Create DataFrame.
Save to CSV.
I will provide two versions in the answer:
A Simple Script: Good for beginners, easy to copy-paste and modify manually.
An Advanced Script: Uses a configuration dictionary to generate the dataset dynamically, which is better for generating different types of datasets without rewriting the generation logic.
Let's stick to one strong, well-commented script that balances simplicity and utility. The "Advanced" approach (using a config dictionary) is usually what people actually want when they ask for a "script to generate datasets" because they want to change columns easily.
Columns to include by default:
id: Unique integer.
name: Fake name.
email: Fake email based on name.
age: Random int between 18 and 90.
salary: Random float.
is_active: Boolean.
join_date: Date within last 5 years.
department: Categorical choice.
Dependencies:pandas, numpy, Faker.
Structure of the output:
Prerequisites (pip install).
The Python Script.
Explanation of how to customize it.
Let's write the code mentally.
python
import pandas as pd
import numpy as np
from faker import Faker
import random
import argparse
def generate_data(num_rows, output_file):
fake = Faker()
data = []
# Options for categorical data
departments = ['Sales', 'Engineering', 'HR', 'Marketing', 'Finance']
for i in range(num_rows):
row = {
'user_id': i + 1,
'name': fake.name(),
'email': fake.email(),
'age': random.randint(18, 65),
'salary': round(random.uniform(40000, 120000), 2),
'join_date': fake.date_between(start_date='-5y', end_date='today'),
'department': random.choice(departments),
'is_active': random.choice([True, False])
}
data.append(row)
df = pd.DataFrame(data)
df.to_csv(output_file, index=False)
print(f"Generated {num_rows} rows in {output_file}")
This is good. I will wrap this in a main block and add argparse so it can be used as a tool.
I will also add a "Schema-based" approach section or comments explaining how to modify it, as users might want specific columns.
Actually, providing a class-based approach is cleaner for importing into other scripts vs running as a standalone tool. I'll stick to the functional approach for the script but write it cleanly.
Let's ensure I check if Faker is installed. No, standard practice is just to tell the user to install it.
Final Polish:
The script should accept arguments for:
Number of rows.
Output filename.
(Optional) Random seed for reproducibility. This is important for "testing". If you generate data for tests, you want the same data every time. I will add random.seed and np.random.seed and Faker.seed.
Refined Code Plan:
Imports.
create_synthetic_dataset(rows, seed) function.
save_to_csv(df, filename) function.
main() using argparse.
This covers all bases. I will present this solution.
Here is a robust, reusable Python script to generate synthetic datasets.
This script uses the Faker library to create realistic data (names, addresses, emails) and Pandas to structure and export the data.
Prerequisites
You will need to install the following libraries:
bash
pip install pandas faker
The Python Script
Save this code as generate_data.py. It is configured with a default schema, but you can easily modify the columns list in the main block to change the data structure.
python
How to use this script
1. Basic Usage
Run the script with default settings (100 rows, output to synthetic_data.csv):
bash
python generate_data.py
2. Specify Rows and Filename
Generate 1,000 rows and save to test_data.csv: