Master NumPy From Scratch

Learn NumPy fundamentals, arrays, indexing, slicing, data types, array operations, broadcasting, mathematical functions, statistics, random numbers, linear algebra, file handling, and practical projects through structured lessons.

COURSE SYLLABUS
1. NumPy Introduction and Installation
Introduction to NumPy NumPy Installation and Setup NumPy Environment and IDE Setup First NumPy Program
2. NumPy Arrays and Array Creation
NumPy Array Fundamentals Array Creation Functions Zeros, Ones and Identity Arrays Range and Linspace Arrays
3. NumPy Array Indexing and Slicing
One-Dimensional Array Indexing Array Slicing Techniques Two-Dimensional Array Indexing Boolean and Fancy Indexing
4. NumPy Data Types and Attributes
NumPy Data Types Array Shape, Size and Dimensions Data Type Conversion and Casting Array Inspection and Attributes
5. NumPy Array Shape and Reshaping
Reshape and Flatten Arrays Transpose and Axis Operations Stacking and Splitting Arrays Expand and Squeeze Dimensions
6. NumPy Array Operations and Broadcasting
Arithmetic Array Operations Comparison and Logical Operations Broadcasting Fundamentals Universal Functions and Vectorization
7. NumPy Mathematical and Statistical Functions
Mathematical Functions Aggregate and Statistical Functions Minimum, Maximum and Percentiles Rounding and Trigonometric Functions
8. NumPy Filtering and Sorting
Array Filtering and Conditions Sorting and Searching Arrays Unique Values and Set Operations Where, Select and Nonzero Functions
9. NumPy Copies and Views
Array Copies and Views Shallow and Deep Copy Concepts Memory Layout and Contiguity Array Iteration and Memory Efficiency
10. NumPy Random Number Generation
Random Generator Fundamentals Random Integers and Sampling Probability Distributions Random Seeds and Simulation
11. NumPy Linear Algebra
Vectors and Matrices Matrix Multiplication and Dot Product Determinants and Matrix Inverse Eigenvalues and Linear Equations
12. NumPy File Input and Output
Importing and Exporting Text Files CSV Data with NumPy Binary Files and NPY Format NPZ Files and Data Persistence
13. NumPy Practical Projects
Student Marks Analysis Project Sales Data Analysis Project Random Simulation Project Image Array Processing Project
14. NumPy Practice and Assessment
NumPy Beginner Practice NumPy Intermediate Exercises NumPy Advanced Challenges Final NumPy Assessment

Sales Data Analysis Project Using NumPy

In this practical project, we will analyze monthly sales data for different products using NumPy. We will calculate total sales, product-wise performance, monthly revenue, average sales, highest and lowest values, month-to-month growth, and sales rankings. We will also filter sales records and export the results to CSV and NPZ files.

1. Project Objectives

After completing this project, you will be able to:

  • Create NumPy arrays representing products and monthly sales.
  • Calculate product-wise and month-wise sales totals.
  • Find average, maximum, and minimum sales.
  • Identify the best-performing product and month.
  • Calculate sales growth between consecutive months.
  • Filter products using Boolean conditions.
  • Sort products according to total sales.
  • Export sales reports to CSV and save arrays in NPZ format.

2. Understand the Project Dataset

Suppose CIIT TRANING INSTITUTE is teaching students how a business can analyze sales data. We will use three sample products and their sales over four months. All values represent sales revenue in rupees.

Product January February March April
Product A 12000 15000 14000 18000
Product B 10000 11000 13000 12500
Product C 8000 9500 10500 12000
Dataset rule: Each row represents a product, and each column represents a month. The values are revenue, not units sold or profit.

3. Import NumPy and Create Sales Arrays

First, import NumPy and create arrays for the product names, month names, and numerical sales data.

import numpy as np products = np.array(["Product A", "Product B", "Product C"]) months = np.array(["January", "February", "March", "April"]) sales = np.array([ [12000, 15000, 14000, 18000], [10000, 11000, 13000, 12500], [8000, 9500, 10500, 12000] ]) print("Products:") print(products) print("\nMonths:") print(months) print("\nSales Data:") print(sales)

Expected Output

Products: ['Product A' 'Product B' 'Product C'] Months: ['January' 'February' 'March' 'April'] Sales Data: [[12000 15000 14000 18000] [10000 11000 13000 12500] [ 8000 9500 10500 12000]]

The array contains 3 rows and 4 columns. Therefore, it stores 12 sales values. NumPy lets us perform calculations on the entire dataset without writing a separate calculation for every product and month.

4. Inspect the Sales Array

Use the shape, ndim, and size attributes to understand the structure of the dataset.

print("Shape:", sales.shape) print("Dimensions:", sales.ndim) print("Number of values:", sales.size) print("Data type:", sales.dtype)

Expected Output

Shape: (3, 4) Dimensions: 2 Number of values: 12 Data type: int64

The displayed integer type may vary by platform or NumPy environment. The important point is that the array stores integer sales values.

5. Calculate Total Sales for Each Product

Use np.sum() with axis=1 to add the monthly values across each product's row.

product_totals = np.sum(sales, axis=1) print("Total sales by product:") print(product_totals) for i in range(len(products)): print(products[i], ":", product_totals[i])

Expected Output

Total sales by product: [59000 46500 40000] Product A : 59000 Product B : 46500 Product C : 40000
Product Total Sales
Product A ₹59,000
Product B ₹46,500
Product C ₹40,000
Remember: axis=1 calculates across each row. Here, it adds January, February, March, and April sales for each product.

6. Calculate Total Sales for Each Month

To calculate monthly totals across all products, use axis=0. NumPy adds the values down each column.

monthly_totals = np.sum(sales, axis=0) print("Monthly totals:") print(monthly_totals) for i in range(len(months)): print(months[i], ":", monthly_totals[i])

Expected Output

Monthly totals: [30000 35500 37500 42500] January : 30000 February : 35500 March : 37500 April : 42500

April has the highest total revenue of ₹42,500, while January has the lowest total revenue of ₹30,000 in this dataset.

7. Calculate Average Sales

The np.mean() function calculates averages. We can calculate the average monthly sales for each product and the average revenue across all products for each month.

product_averages = np.mean(sales, axis=1) monthly_averages = np.mean(sales, axis=0) print("Average sales by product:") print(np.round(product_averages, 2)) print("\nAverage sales by month:") print(np.round(monthly_averages, 2))

Expected Output

Average sales by product: [14750. 11625. 10000.] Average sales by month: [10000. 11833.33 12500. 14166.67]

Product A has average monthly sales of ₹14,750. The average sales per product in April are approximately ₹14,166.67.

8. Find the Highest and Lowest Sales

Use np.max() and np.min() to find the highest and lowest monthly sales for every product.

highest_by_product = np.max(sales, axis=1) lowest_by_product = np.min(sales, axis=1) print("Highest monthly sales:") print(highest_by_product) print("\nLowest monthly sales:") print(lowest_by_product) overall_highest = np.max(sales) overall_lowest = np.min(sales) print("\nHighest value in dataset:", overall_highest) print("Lowest value in dataset:", overall_lowest)

Expected Output

Highest monthly sales: [18000 13000 12000] Lowest monthly sales: [12000 10000 8000] Highest value in dataset: 18000 Lowest value in dataset: 8000

Product A's highest monthly revenue is ₹18,000. The lowest value in the entire dataset is ₹8,000 for Product C.

9. Identify the Best-Performing Product

The np.argmax() function returns the index of the largest value. Use this index to find the product with the highest total sales.

best_product_index = np.argmax(product_totals) print("Best-performing product:", products[best_product_index]) print("Total sales:", product_totals[best_product_index])

Expected Output

Best-performing product: Product A Total sales: 59000

Product A is the best-performing product by total revenue during the four-month period. This conclusion is based on revenue alone and does not account for costs or profit margins.

10. Find the Best and Worst Sales Months

Apply np.argmax() and np.argmin() to the monthly totals. These functions return the positions of the largest and smallest values.

best_month_index = np.argmax(monthly_totals) worst_month_index = np.argmin(monthly_totals) print("Best sales month:", months[best_month_index]) print("Best monthly revenue:", monthly_totals[best_month_index]) print("\nLowest sales month:", months[worst_month_index]) print("Lowest monthly revenue:", monthly_totals[worst_month_index])

Expected Output

Best sales month: April Best monthly revenue: 42500 Lowest sales month: January Lowest monthly revenue: 30000

11. Calculate Month-to-Month Sales Growth

Use np.diff() to calculate the difference between consecutive monthly totals. Positive differences represent an increase, while negative differences represent a decrease.

monthly_change = np.diff(monthly_totals) print("Month-to-month change:") print(monthly_change)

Expected Output

Month-to-month change: [5500 2000 5000]

Revenue increased by ₹5,500 from January to February, by ₹2,000 from February to March, and by ₹5,000 from March to April.

Calculate Percentage Growth

To calculate percentage growth, divide each difference by the previous month's total and multiply by 100.

growth_percentage = ( np.diff(monthly_totals) / monthly_totals[:-1] ) * 100 print("Growth percentages:") print(np.round(growth_percentage, 2))

Expected Output

Growth percentages: [18.33 5.63 13.33]

These percentages represent January-to-February, February-to-March, and March-to-April growth, respectively.

Important: Percentage growth requires dividing by the previous period's value. If that value is zero, handle the division separately to avoid invalid results.

12. Filter Products Using Conditions

Boolean indexing lets us select values based on a condition. In this example, we select products whose total sales are greater than ₹45,000.

high_sales_mask = product_totals > 45000 high_sales_products = products[high_sales_mask] high_sales_totals = product_totals[high_sales_mask] print("Products with sales above 45000:") print(high_sales_products) print("Their total sales:") print(high_sales_totals)

Expected Output

Products with sales above 45000: ['Product A' 'Product B'] Their total sales: [59000 46500]

Filter Individual Monthly Values

You can also select sales values above ₹12,000 from the complete two-dimensional array.

high_monthly_values = sales[sales > 12000] print(high_monthly_values)

Expected Output

[15000 14000 18000 13000 12500]

When a Boolean condition is applied directly to a two-dimensional array, the selected values are returned as a one-dimensional array.

13. Sort Products by Total Sales

Use np.argsort() to obtain the indices that would sort product totals. Reverse the indices to display products from highest to lowest sales.

ranking = np.argsort(product_totals)[::-1] print("Product ranking:") for position, index in enumerate(ranking, start=1): print( position, products[index], "- Total Sales:", product_totals[index] )

Expected Output

Product ranking: 1 Product A - Total Sales: 59000 2 Product B - Total Sales: 46500 3 Product C - Total Sales: 40000
Remember: np.argsort() returns indices, not product names. Use the returned indices to retrieve the matching product names and totals.

14. Calculate Each Product's Contribution

We can calculate the percentage contribution of each product to total revenue. First, find the sum of all product totals, then divide each product total by that sum.

grand_total = np.sum(product_totals) product_contribution = ( product_totals / grand_total ) * 100 print("Grand total:", grand_total) print("Contribution percentages:") print(np.round(product_contribution, 2))

Expected Output

Grand total: 145500 Contribution percentages: [40.55 31.96 27.49]

Product A contributes approximately 40.55% of the total revenue, followed by Product B at 31.96% and Product C at 27.49%.

15. Export the Sales Report to CSV

NumPy performs the calculations, while Python's built-in csv module writes product names, monthly sales, and calculated totals into a spreadsheet-friendly file.

import csv with open( "sales_analysis_report.csv", "w", newline="", encoding="utf-8" ) as file: writer = csv.writer(file) writer.writerow([ "Product", "January", "February", "March", "April", "Total Sales", "Average Sales" ]) for i in range(len(products)): writer.writerow([ products[i], *sales[i], product_totals[i], round(product_averages[i], 2) ]) print("Sales report saved successfully.")

Expected Output

Sales report saved successfully.

The file sales_analysis_report.csv is created in the current working directory. You can open it in a spreadsheet application to inspect or share the report.

File location: If you cannot find the CSV file, check the current working directory of your Python environment. This code does not automatically save the file inside your ASP.NET application.

16. Save and Load Sales Data Using NPZ

The NPZ format stores multiple NumPy arrays in a single archive. This is useful when you want to preserve both the original sales data and the calculated results.

np.savez_compressed( "sales_analysis_data.npz", products=products, months=months, sales=sales, product_totals=product_totals, monthly_totals=monthly_totals, product_averages=product_averages, growth_percentage=growth_percentage ) print("Sales data saved successfully.") with np.load("sales_analysis_data.npz") as data: loaded_products = data["products"] loaded_sales = data["sales"] loaded_totals = data["product_totals"] print("Loaded products:", loaded_products) print("Loaded sales data:") print(loaded_sales) print("Loaded product totals:", loaded_totals)

Expected Output

Sales data saved successfully. Loaded products: ['Product A' 'Product B' 'Product C'] Loaded sales data: [[12000 15000 14000 18000] [10000 11000 13000 12500] [ 8000 9500 10500 12000]] Loaded product totals: [59000 46500 40000]
Tip: Use np.save() for one array, np.savez() for multiple arrays, and np.savez_compressed() to compress the saved archive.

17. Complete Project Code

The following script combines the main analysis operations, rankings, growth calculations, CSV export, and NPZ saving into one runnable program.

import numpy as np import csv # 1. Create the dataset products = np.array(["Product A", "Product B", "Product C"]) months = np.array(["January", "February", "March", "April"]) sales = np.array([ [12000, 15000, 14000, 18000], [10000, 11000, 13000, 12500], [8000, 9500, 10500, 12000] ]) # 2. Product-wise analysis product_totals = np.sum(sales, axis=1) product_averages = np.mean(sales, axis=1) product_highest = np.max(sales, axis=1) product_lowest = np.min(sales, axis=1) # 3. Month-wise analysis monthly_totals = np.sum(sales, axis=0) monthly_averages = np.mean(sales, axis=0) # 4. Overall analysis grand_total = np.sum(sales) overall_average = np.mean(sales) print("SALES ANALYSIS REPORT") print("-" * 55) for i in range(len(products)): print( f"{products[i]} | " f"Total: Rs. {product_totals[i]} | " f"Average: Rs. {product_averages[i]:.2f} | " f"Highest: Rs. {product_highest[i]} | " f"Lowest: Rs. {product_lowest[i]}" ) print("\nMONTHLY TOTALS") for i in range(len(months)): print(f"{months[i]}: Rs. {monthly_totals[i]}") # 5. Identify best product and month best_product_index = np.argmax(product_totals) best_month_index = np.argmax(monthly_totals) print("\nBest product:", products[best_product_index]) print("Best month:", months[best_month_index]) # 6. Calculate growth monthly_change = np.diff(monthly_totals) growth_percentage = ( monthly_change / monthly_totals[:-1] ) * 100 print("\nMonth-to-month change:", monthly_change) print("Growth percentages:", np.round(growth_percentage, 2)) # 7. Rank products ranking = np.argsort(product_totals)[::-1] print("\nPRODUCT RANKING") for position, index in enumerate(ranking, start=1): print( f"{position}. {products[index]} - " f"Rs. {product_totals[index]}" ) # 8. Export CSV report with open( "sales_analysis_report.csv", "w", newline="", encoding="utf-8" ) as file: writer = csv.writer(file) writer.writerow([ "Product", "January", "February", "March", "April", "Total Sales", "Average Sales" ]) for i in range(len(products)): writer.writerow([ products[i], *sales[i], product_totals[i], round(product_averages[i], 2) ]) # 9. Save NumPy arrays np.savez_compressed( "sales_analysis_data.npz", products=products, months=months, sales=sales, product_totals=product_totals, monthly_totals=monthly_totals, product_averages=product_averages, growth_percentage=growth_percentage ) print("\nCSV report and NPZ data saved successfully.")

Run the script in your Python environment. It prints the sales report and creates sales_analysis_report.csv and sales_analysis_data.npz in the current working directory.

18. Common Mistakes

Mistake 1: Using the wrong axis

axis=1 calculates across each product's row. axis=0 calculates down the columns to produce month-wise results.

Mistake 2: Confusing revenue with profit

Sales revenue is the amount earned from sales. Profit requires cost information as well. This dataset does not include costs, so it cannot determine profit.

Mistake 3: Sorting totals without preserving product names

np.argsort() returns indices. Use the same indices to access both the product names and their totals.

Mistake 4: Misinterpreting np.diff()

np.diff() returns absolute differences, not percentages. Divide each difference by the previous value and multiply by 100 to calculate growth rates.

Mistake 5: Expecting CSV or NPZ files in a specific folder

Relative filenames are saved in the current working directory. Use an explicit path when you need the files to be stored in a particular location.

19. Practice Exercises

  1. Add May sales for all three products and update the analysis.
  2. Find the product with the lowest total revenue.
  3. Calculate each product's percentage contribution to grand total sales.
  4. Display only products whose total sales exceed ₹45,000.
  5. Find the month with the largest increase in revenue.
  6. Calculate the difference between the highest and lowest monthly totals.
  7. Change Product C's March sales to ₹15,000 and recalculate the report.
  8. Load the NPZ archive and print the saved monthly totals.
  9. Extend the dataset to six months and calculate the growth percentages.

Summary

In this project, you used NumPy arrays to analyze product-wise and month-wise sales, calculate totals and averages, identify highest and lowest values, measure month-to-month changes, filter records, rank products, and calculate revenue contributions.

You also exported a report to CSV and saved the numerical dataset in compressed NPZ format. These techniques can be adapted to business reports, inventory analysis, monthly revenue tracking, and other numerical data-analysis tasks.