Got it!
I’ll design 10 practical problem statements that use data structures,
functions, and import/export in a data analytical tool — Python with Pandas is a
perfect example.
I’ll give you each problem statement with a sample Python code snippet to show how
to run it practically.
1. Calculate Total Sales from CSV File
Problem: Import sales data from a CSV file, use DataFrame to store it, write a
function to calculate total sales, and export the result to a new CSV.
python
Copy
Edit
import pandas as pd
# Load CSV
df = pd.read_csv('sales_data.csv')
# Function to calculate total sales
def total_sales(data):
return data['Amount'].sum()
# Calculate total sales
total = total_sales(df)
print(f"Total Sales: {total}")
# Export total sales to a CSV
[Link]({'Total Sales': [total]}).to_csv('total_sales.csv', index=False)
2. Average Customer Rating from JSON File
Problem: Import JSON data with customer ratings, store in DataFrame, write function
to calculate average rating, export average to JSON.
python
Copy
Edit
import pandas as pd
df = pd.read_json('customer_ratings.json')
def average_rating(data):
return data['Rating'].mean()
avg = average_rating(df)
print(f"Average Rating: {avg}")
# Export average rating to JSON
[Link]({'Average Rating': [avg]}).to_json('avg_rating.json',
orient='records')
3. Employee Attendance Percentage
Problem: Import attendance data from Excel, calculate attendance percentage per
employee, export summary to Excel.
python
Copy
Edit
import pandas as pd
df = pd.read_excel('[Link]')
def attendance_percentage(data):
total_days = [Link][0]
attendance = [Link]('Employee')['Status'].apply(lambda x: (x ==
'Present').sum())
percentage = (attendance / total_days) * 100
return percentage.reset_index(name='Attendance Percentage')
attendance_df = attendance_percentage(df)
print(attendance_df)
attendance_df.to_excel('attendance_summary.xlsx', index=False)
4. Calculate Moving Average on Stock Prices
Problem: Import stock price data, calculate moving average using a function, export
result to CSV.
python
Copy
Edit
import pandas as pd
df = pd.read_csv('stock_prices.csv')
def moving_average(data, window):
data['Moving Average'] = data['Close'].rolling(window=window).mean()
return data
df_ma = moving_average(df, 5)
print(df_ma.head())
df_ma.to_csv('stock_ma.csv', index=False)
5. Clean Sales Data and Export Cleaned Version
Problem: Import messy sales CSV, clean missing data using a function, export
cleaned data.
python
Copy
Edit
import pandas as pd
df = pd.read_csv('raw_sales.csv')
def clean_data(data):
# Drop rows where Amount is missing or negative
cleaned = [Link](subset=['Amount'])
cleaned = cleaned[cleaned['Amount'] >= 0]
return cleaned
cleaned_df = clean_data(df)
print(cleaned_df.head())
cleaned_df.to_csv('cleaned_sales.csv', index=False)
6. Generate Movie Recommendations (Simple User Similarity)
Problem: Import movie ratings CSV, calculate similarity between users, export
recommendations.
python
Copy
Edit
import pandas as pd
df = pd.read_csv('movie_ratings.csv')
def user_similarity(data, user1, user2):
# Calculate similarity as correlation between ratings of two users
ratings1 = data[data['UserID'] == user1][['MovieID', 'Rating']]
ratings2 = data[data['UserID'] == user2][['MovieID', 'Rating']]
merged = [Link](ratings1, ratings2, on='MovieID', suffixes=('_u1', '_u2'))
return merged['Rating_u1'].corr(merged['Rating_u2'])
similarity = user_similarity(df, 1, 2)
print(f"User similarity between 1 and 2: {similarity}")
# Export similarity to JSON
[Link]({'User1': [1], 'User2': [2], 'Similarity':
[similarity]}).to_json('user_similarity.json', orient='records')
7. Aggregate Daily Weather Data
Problem: Import weather CSV, calculate daily averages, export summarized data.
python
Copy
Edit
import pandas as pd
df = pd.read_csv('weather_data.csv')
def daily_average(data):
return [Link]('Date').agg({'Temperature': 'mean', 'Humidity':
'mean'}).reset_index()
daily_avg = daily_average(df)
print(daily_avg.head())
daily_avg.to_csv('daily_weather_avg.csv', index=False)
8. Optimize Portfolio Returns
Problem: Import asset prices CSV, calculate portfolio return using weights, export
result.
python
Copy
Edit
import pandas as pd
import numpy as np
df = pd.read_csv('asset_prices.csv', index_col='Date')
def portfolio_return(data, weights):
returns = data.pct_change().dropna()
port_return = (returns * weights).sum(axis=1)
return port_return
weights = [Link]([0.4, 0.3, 0.3]) # example weights for 3 assets
port_returns = portfolio_return(df, weights)
print(port_returns.head())
port_returns.to_csv('portfolio_returns.csv')
9. Calculate Student GPA
Problem: Import grades from Excel, calculate GPA using function, export GPA report.
python
Copy
Edit
import pandas as pd
df = pd.read_excel('student_grades.xlsx')
def calculate_gpa(data):
grade_points = {'A':4, 'B':3, 'C':2, 'D':1, 'F':0}
data['Points'] = data['Grade'].map(grade_points)
gpa = [Link]('StudentID')['Points'].mean().reset_index(name='GPA')
return gpa
gpa_df = calculate_gpa(df)
print(gpa_df)
gpa_df.to_excel('student_gpa.xlsx', index=False)
10. Aggregate Traffic Data by Hour
Problem: Import traffic CSV, aggregate counts by hour, export result.
python
Copy
Edit
import pandas as pd
df = pd.read_csv('traffic_data.csv')
def hourly_aggregation(data):
data['Hour'] = pd.to_datetime(data['Timestamp']).[Link]
return [Link]('Hour')['VehicleCount'].sum().reset_index()
hourly_traffic = hourly_aggregation(df)
print(hourly_traffic)
hourly_traffic.to_csv('hourly_traffic.csv', index=False)
How to run these examples?
Save your data files (sales_data.csv, customer_ratings.json, etc.) in your working
directory.
Install Python and Pandas (pip install pandas).
Copy the corresponding code into a .py file (e.g., [Link]).
Run in terminal:
bash
Copy
Edit
python [Link]
Check the output files generated (CSV, Excel, JSON) in your working directory.
If you want, I can help you set up a sample dataset for any of these or explain how
to run it step-by-step! Would you like that?
You said:
what is import and export data
ChatGPT said:
Great question!
What is Importing Data?
Importing data means bringing data from an external file or source into your
program or data analysis tool so you can work with it.
For example, loading data from a CSV file, Excel file, JSON file, or a database
into Python, R, Excel, or any analytical tool.
This lets you read data that was stored somewhere else and use it for analysis,
cleaning, visualization, etc.
What is Exporting Data?
Exporting data means saving or writing the processed data or results from your
program or tool to an external file so it can be used later, shared, or imported
into another tool.
For example, saving a cleaned dataset or analysis results back into a CSV, Excel,
JSON file, or database.
This lets you save your output or intermediate results so they are not lost and can
be used elsewhere.
Simple analogy:
Importing = Reading a book from the library into your hands.
Exporting = Writing your notes and putting them in your backpack to take home.
Example in Python (with CSV):
python
Copy
Edit
import pandas as pd
# Import data (read CSV file)
data = pd.read_csv('input_data.csv')
# Process data
summary = [Link]()
# Export data (write to CSV file)
summary.to_csv('summary_output.csv')
If you want, I can explain importing/exporting in a specific tool like Excel or SQL
too!
You said:
also show csv file created and output also show
ChatGPT said:
Sure! Let's take Problem 1: Calculate Total Sales from CSV File as an example and
walk through:
The CSV input file content.
The Python code to import, process, export.
The output CSV file content.
The printed output you see on running the code.
1. CSV Input file (sales_data.csv)
OrderID Product Amount
1001 Widget A 250
1002 Widget B 150
1003 Widget A 200
1004 Widget C 300
Save this as sales_data.csv
2. Python Code
python
Copy
Edit
import pandas as pd
# Step 1: Import CSV
df = pd.read_csv('sales_data.csv')
# Step 2: Define function to calculate total sales
def total_sales(data):
return data['Amount'].sum()
# Step 3: Calculate total sales
total = total_sales(df)
print(f"Total Sales: {total}")
# Step 4: Export the total sales to a new CSV
[Link]({'Total Sales': [total]}).to_csv('total_sales.csv', index=False)
3. Output CSV file (total_sales.csv)
Total Sales
900
4. Printed Output on running the script:
yaml
Copy
Edit
Total Sales: 900
How to run:
Save the CSV input file as sales_data.csv in the same folder as your Python script.
Run the Python script (python [Link]).
Check the terminal for the printed total sales.
Check the folder for the newly created total_sales.csv file with the summary.
If you'd like, I can generate the CSV files and show you how they look as files or
display more examples! Want me to?
ChatGPT said:
Here’s a complete practical example, including:
✅ CSV input file content
✅ Python code
✅ Output CSV file
✅ Printed output
Let’s go step by step 👇
✅ STEP 1: Create Input CSV File (sales_data.csv)
Create a file named sales_data.csv with the following contents:
csv
Copy
Edit
OrderID,Product,Amount
1001,Widget A,250
1002,Widget B,150
1003,Widget A,200
1004,Widget C,300
📝 How to create it:
Open a text editor or Excel
Paste the above content
Save it as sales_data.csv in your project folder
✅ STEP 2: Python Code to Import, Process, and Export
Save this as total_sales.py:
python
Copy
Edit
import pandas as pd
# Step 1: Import CSV
df = pd.read_csv('sales_data.csv')
# Step 2: Function to calculate total sales
def total_sales(data):
return data['Amount'].sum()
# Step 3: Calculate total
total = total_sales(df)
print(f"Total Sales: {total}")
# Step 4: Export result to CSV
[Link]({'Total Sales': [total]}).to_csv('total_sales.csv', index=False)
✅ STEP 3: Run the Code
In the terminal, run:
bash
Copy
Edit
python total_sales.py
You’ll see this output in the terminal:
yaml
Copy
Edit
Total Sales: 900
✅ STEP 4: Output CSV File (total_sales.csv)
After running the script, a new file named total_sales.csv will be created with
this content:
c
Copy
Edit
Total Sales
900
🧠 Summary of What Happened:
Action Result
Import Read sales_data.csv
Data structure Used Pandas DataFrame
Function total_sales() to compute
Export Saved result to CSV