Skip to content

Food Delivery Data Analysis Using Python | Class 12 IP Project

Food Delivery Data Analysis Using Python | Class 12 IP Project

main_food_delivery.py

import pandas as pd
from analysis_food_delivery import perform_analysis, show_graphs, export_detailed_reports

def signup():
    try:
        users = pd.read_csv("users.csv")
    except FileNotFoundError:
        users = pd.DataFrame(columns=["username", "password"])

    username = input("Enter new username: ")
    password = input("Enter new password: ")

    if username in users['username'].values:
        print("⚠️ Username already exists!")
    else:
        pd.DataFrame([[username, password]], columns=['username', 'password']).to_csv(
            'users.csv', mode='a', index=False, header=not pd.io.common.file_exists('users.csv'))
        print("✅ Signup successful!")

def login():
    try:
        users = pd.read_csv("users.csv")
    except FileNotFoundError:
        print("⚠️ No user database found. Please sign up first!")
        return

    username = input("Enter username: ")
    password = input("Enter password: ")

    if ((users['username'] == username) & (users['password'] == password)).any():
        print(f"\n✅ Welcome {username}! Login Successful.")
        main_menu()
    else:
        print("❌ Invalid credentials! Please try again.")
def add_order():
    try:
        df = pd.read_csv("food_data.csv")
    except FileNotFoundError:
        print("⚠️ food_data.csv not found!")
        return

    try:
        oid = int(input("Enter Order ID: "))
        name = input("Enter Customer Name: ")
        city = input("Enter City: ")
        item = input("Enter Food Item: ")
        qty = int(input("Enter Quantity: "))
        price = float(input("Enter Price per Item: "))
        time = int(input("Enter Delivery Time (min): "))
        rating = float(input("Enter Rating (out of 5): "))

        new = pd.DataFrame([[oid, name, city, item, qty, price, time, rating]], columns=df.columns)
        df = pd.concat([df, new], ignore_index=True)
        df.to_csv("food_data.csv", index=False)
        print("✅ Order added successfully!")
    except Exception as e:
        print("⚠️ Error:", e)

def update_order():
    try:
        df = pd.read_csv("food_data.csv")
    except FileNotFoundError:
        print("⚠️ food_data.csv not found!")
        return

    oid = int(input("Enter Order ID to update: "))
    if oid not in df['Order_ID'].values:
        print("❌ Order ID not found!")
        return

    print("\nWhat do you want to update?")
    print("1. City\n2. Food Item\n3. Quantity\n4. Price\n5. Delivery Time\n6. Rating")
    choice = input("Enter choice: ")

    if choice == '1':
        df.loc[df['Order_ID'] == oid, 'City'] = input("Enter new City: ")
    elif choice == '2':
        df.loc[df['Order_ID'] == oid, 'Food_Item'] = input("Enter new Food Item: ")
    elif choice == '3':
        df.loc[df['Order_ID'] == oid, 'Quantity'] = int(input("Enter new Quantity: "))
    elif choice == '4':
        df.loc[df['Order_ID'] == oid, 'Price'] = float(input("Enter new Price: "))
    elif choice == '5':
        df.loc[df['Order_ID'] == oid, 'Delivery_Time(min)'] = int(input("Enter new Time: "))
    elif choice == '6':
        df.loc[df['Order_ID'] == oid, 'Rating'] = float(input("Enter new Rating: "))
    else:
        print("⚠️ Invalid choice!")
        return

    df.to_csv("food_data.csv", index=False)
    print("✅ Order updated successfully!")

def delete_order():
    try:
        df = pd.read_csv("food_data.csv")
    except FileNotFoundError:
        print("⚠️ food_data.csv not found!")
        return

    oid = int(input("Enter Order ID to delete: "))
    if oid not in df['Order_ID'].values:
        print("❌ Order ID not found!")
        return

    df = df[df['Order_ID'] != oid]
    df.to_csv("food_data.csv", index=False)
    print("✅ Order deleted successfully!")
def main_menu():
    while True:
        print("\n========= FOOD DELIVERY ANALYSIS =========")
        print("1. View Data")
        print("2. Add Order")
        print("3. Update Order")
        print("4. Delete Order")
        print("5. Perform Analysis")
        print("6. Show Graphs")
        print("7. Export Reports")
        print("8. Logout")

        choice = input("Enter choice: ")

        if choice == '1':
            try:
                df = pd.read_csv("food_data.csv")
                print(df)
            except:
                print("⚠️ CSV file not found!")
        elif choice == '2':
            add_order()
        elif choice == '3':
            update_order()
        elif choice == '4':
            delete_order()
        elif choice == '5':
            perform_analysis()
        elif choice == '6':
            show_graphs()
        elif choice == '7':
            export_detailed_reports()
        elif choice == '8':
            print("👋 Logged out successfully.")
            break
        else:
            print("⚠️ Invalid choice! Try again.")

while True:
    print("\n======= Welcome to Food Delivery System =======")
    print("1. Login")
    print("2. Signup")
    print("3. Exit")

    option = input("Enter your choice: ")

    if option == '1':
        login()
    elif option == '2':
        signup()
    elif option == '3':
        print("👋 Thank you for using Food Delivery Analysis!")
        break
    else:
        print("⚠️ Invalid input! Try again.")
    

analysis_food_delivery.py

# --------------------------------------------------------
# FOOD DELIVERY ANALYSIS - ANALYSIS FILE
# --------------------------------------------------------
import pandas as pd
import matplotlib.pyplot as plt

# --------------------------------------------------------
# BASIC ANALYSIS
# --------------------------------------------------------
def perform_analysis():
    df = pd.read_csv("food_data.csv")
    df['Revenue'] = df['Quantity'] * df['Price']

    print("\n--- TOTAL REVENUE BY CITY ---")
    print(df.groupby('City')['Revenue'].sum())

    print("\n--- AVERAGE RATING BY FOOD ITEM ---")
    print(df.groupby('Food_Item')['Rating'].mean())

    print("\n--- AVERAGE DELIVERY TIME ---")
    print(df.groupby('City')['Delivery_Time(min)'].mean())

    print("\n--- MOST POPULAR FOOD ITEM ---")
    print(df['Food_Item'].value_counts().head(3))

    print("\n--- TOP CUSTOMERS BY SPENDING ---")
    print(df.groupby('Customer_Name')['Revenue'].sum().sort_values(ascending=False).head(3))

# --------------------------------------------------------
# VISUAL ANALYSIS
# --------------------------------------------------------
def show_graphs():
    df = pd.read_csv("food_data.csv")
    df['Revenue'] = df['Quantity'] * df['Price']

    # Bar Chart: Revenue per Food Item
    df.groupby('Food_Item')['Revenue'].sum().plot(kind='bar', color='orange')
    plt.title("Total Revenue per Food Item")
    plt.xlabel("Food Item")
    plt.ylabel("Revenue (₹)")
    plt.show()

    # Pie Chart: Orders per City
    df['City'].value_counts().plot(kind='pie', autopct='%1.1f%%', startangle=90)
    plt.title("Orders Distribution by City")
    plt.ylabel("")
    plt.show()

    # Line Graph: Average Delivery Time per City
    df.groupby('City')['Delivery_Time(min)'].mean().plot(kind='line', marker='o', color='green')
    plt.title("Average Delivery Time by City")
    plt.xlabel("City")
    plt.ylabel("Avg Delivery Time (min)")
    plt.grid(True)
    plt.show()

# --------------------------------------------------------
# EXPORT REPORT
# --------------------------------------------------------
def export_detailed_reports():
    df = pd.read_csv("food_data.csv")
    df['Revenue'] = df['Quantity'] * df['Price']

    summary = {
        "Total Orders": len(df),
        "Total Revenue": df['Revenue'].sum(),
        "Average Rating": df['Rating'].mean(),
        "Average Delivery Time": df['Delivery_Time(min)'].mean(),
        "Top Food Item": df['Food_Item'].value_counts().idxmax(),
    }

    pd.DataFrame([summary]).to_csv("analysis_report.csv", index=False)
    print("✅ Report exported successfully as analysis_report.csv!")