Skip to content

First NumPy Program

In this chapter, we'll write our first NumPy program and experience NumPy's powerful features through practical code examples.

Hello NumPy

Let's start with the simplest NumPy program:

python
# Import NumPy library
import numpy as np

# Create our first array
my_array = np.array([1, 2, 3, 4, 5])

# Print the array
print("My first NumPy array:")
print(my_array)

# Print array type
print(f"Array type: {type(my_array)}")

# Print array shape
print(f"Array shape: {my_array.shape}")

Output:

My first NumPy array:
[1 2 3 4 5]
Array type: <class 'numpy.ndarray'>
Array shape: (5,)

Basic Array Operations

Creating Different Types of Arrays

python
import numpy as np

# 1D array
array_1d = np.array([1, 2, 3, 4, 5])
print("1D array:", array_1d)

# 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("2D array:")
print(array_2d)

# 3D array
array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("3D array:")
print(array_3d)

Output:

1D array: [1 2 3 4 5]
2D array:
[[1 2 3]
 [4 5 6]]
3D array:
[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]

Using Built-in Functions to Create Arrays

python
import numpy as np

# Create all-zeros array
zeros_array = np.zeros(5)
print("All-zeros array:", zeros_array)

# Create all-ones array
ones_array = np.ones((2, 3))
print("All-ones array:")
print(ones_array)

# Create arithmetic sequence
range_array = np.arange(0, 10, 2)
print("Arithmetic sequence:", range_array)

# Create evenly spaced array
linspace_array = np.linspace(0, 1, 5)
print("Evenly spaced array:", linspace_array)

# Create random array
random_array = np.random.random(5)
print("Random array:", random_array)

Output:

All-zeros array: [0. 0. 0. 0. 0.]
All-ones array:
[[1. 1. 1.]
 [1. 1. 1.]]
Arithmetic sequence: [0 2 4 6 8]
Evenly spaced array: [0.   0.25 0.5  0.75 1.  ]
Random array: [0.37454012 0.95071431 0.73199394 0.59865848 0.15601864]

Basic Array Properties

python
import numpy as np

# Create a 2D array
array = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

print("Original array:")
print(array)
print()

# Basic array properties
print(f"Array dimensions: {array.ndim}")
print(f"Array shape: {array.shape}")
print(f"Array size: {array.size}")
print(f"Data type: {array.dtype}")
print(f"Bytes per element: {array.itemsize}")
print(f"Total bytes: {array.nbytes}")

Output:

Original array:
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]

Array dimensions: 2
Array shape: (3, 4)
Array size: 12
Data type: int32
Bytes per element: 4
Total bytes: 48

Basic Mathematical Operations

Array and Scalar Operations

python
import numpy as np

# Create array
array = np.array([1, 2, 3, 4, 5])
print("Original array:", array)

# Addition
print("Add 10:", array + 10)

# Multiplication
print("Multiply by 2:", array * 2)

# Power
print("Square:", array ** 2)

# Division
print("Divide by 2:", array / 2)

Output:

Original array: [1 2 3 4 5]
Add 10: [11 12 13 14 15]
Multiply by 2: [ 2  4  6  8 10]
Square: [ 1  4  9 16 25]
Divide by 2: [0.5 1.  1.5 2.  2.5]

Array and Array Operations

python
import numpy as np

# Create two arrays
array1 = np.array([1, 2, 3, 4, 5])
array2 = np.array([10, 20, 30, 40, 50])

print("Array 1:", array1)
print("Array 2:", array2)
print()

# Element-wise operations
print("Addition:", array1 + array2)
print("Subtraction:", array2 - array1)
print("Multiplication:", array1 * array2)
print("Division:", array2 / array1)

Output:

Array 1: [1 2 3 4 5]
Array 2: [10 20 30 40 50]

Addition: [11 22 33 44 55]
Subtraction: [ 9 18 27 36 45]
Multiplication: [ 10  40  90 160 250]
Division: [10. 10. 10. 10. 10.]

Array Indexing and Slicing

1D Array Indexing

python
import numpy as np

# Create array
array = np.array([10, 20, 30, 40, 50])
print("Original array:", array)

# Forward indexing
print("First element:", array[0])
print("Third element:", array[2])

# Reverse indexing
print("Last element:", array[-1])
print("Second to last:", array[-2])

# Slicing
print("First three elements:", array[:3])
print("Last three elements:", array[-3:])
print("Middle elements:", array[1:4])
print("Every other element:", array[::2])

Output:

Original array: [10 20 30 40 50]
First element: 10
Third element: 30
Last element: 50
Second to last: 40
First three elements: [10 20 30]
Last three elements: [30 40 50]
Middle elements: [20 30 40]
Every other element: [10 30 50]

2D Array Indexing

python
import numpy as np

# Create 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("2D array:")
print(array_2d)
print()

# Access single element
print("Row 1, Col 1:", array_2d[0, 0])
print("Row 2, Col 3:", array_2d[1, 2])
print("Last row, last col:", array_2d[-1, -1])

# Access entire row or column
print("First row:", array_2d[0, :])
print("Second column:", array_2d[:, 1])

# Slicing
print("First two rows, first two cols:")
print(array_2d[:2, :2])

Output:

2D array:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Row 1, Col 1: 1
Row 2, Col 3: 6
Last row, last col: 9
First row: [1 2 3]
Second column: [2 5 8]
First two rows, first two cols:
[[1 2]
 [4 5]]

Common Mathematical Functions

python
import numpy as np

# Create array
array = np.array([1, 4, 9, 16, 25])
print("Original array:", array)

# Math functions
print("Square root:", np.sqrt(array))
print("Logarithm:", np.log(array))
print("Exponential:", np.exp([1, 2, 3]))

# Trigonometric functions
angles = np.array([0, np.pi/4, np.pi/2, np.pi])
print("Angles:", angles)
print("Sine:", np.sin(angles))
print("Cosine:", np.cos(angles))

# Statistical functions
data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print("Data:", data)
print("Mean:", np.mean(data))
print("Standard deviation:", np.std(data))
print("Maximum:", np.max(data))
print("Minimum:", np.min(data))
print("Sum:", np.sum(data))

Output:

Original array: [ 1  4  9 16 25]
Square root: [1. 2. 3. 4. 5.]
Logarithm: [0.         1.38629436 2.19722458 2.77258872 3.21887582]
Exponential: [ 2.71828183  7.3890561  20.08553692]
Angles: [0.         0.78539816 1.57079633 3.14159265]
Sine: [0.0000000e+00 7.0710678e-01 1.0000000e+00 1.2246468e-16]
Cosine: [ 1.00000000e+00  7.07106781e-01  6.12323400e-17 -1.00000000e+00]
Data: [ 1  2  3  4  5  6  7  8  9 10]
Mean: 5.5
Standard deviation: 2.8722813232690143
Maximum: 10
Minimum: 1
Sum: 55

Practical Examples

Example 1: Student Grade Statistics

python
import numpy as np

# Student grade data (5 students, 3 subjects)
scores = np.array([
    [85, 92, 78],  # Student 1
    [90, 88, 85],  # Student 2
    [78, 85, 92],  # Student 3
    [92, 90, 88],  # Student 4
    [88, 85, 90]   # Student 5
])

print("Student scores:")
print(scores)
print()

# Calculate each student's average
student_avg = np.mean(scores, axis=1)
print("Each student's average:", student_avg)

# Calculate each subject's average
subject_avg = np.mean(scores, axis=0)
print("Each subject's average:", subject_avg)

# Find highest and lowest scores
print(f"Highest score: {np.max(scores)}")
print(f"Lowest score: {np.min(scores)}")

# Calculate overall average
overall_avg = np.mean(scores)
print(f"Overall average: {overall_avg:.2f}")

Output:

Student scores:
[[85 92 78]
 [90 88 85]
 [78 85 92]
 [92 90 88]
 [88 85 90]]

Each student's average: [85.         87.66666667 85.         90.         87.66666667]
Each subject's average: [86.6 88.  86.6]
Highest score: 92
Lowest score: 78
Overall average: 87.00

Example 2: Simple Data Analysis

python
import numpy as np

# Simulate weekly temperature data
temperatures = np.array([22, 25, 28, 30, 27, 24, 21])
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

print("Weekly temperature data:")
for day, temp in zip(days, temperatures):
    print(f"{day}: {temp}°C")
print()

# Statistical analysis
print(f"Average temperature: {np.mean(temperatures):.1f}°C")
print(f"Maximum temperature: {np.max(temperatures)}°C")
print(f"Minimum temperature: {np.min(temperatures)}°C")
print(f"Temperature range: {np.max(temperatures) - np.min(temperatures)}°C")
print(f"Standard deviation: {np.std(temperatures):.2f}°C")

# Find days above average
avg_temp = np.mean(temperatures)
high_temp_days = temperatures > avg_temp
print(f"\nDays above average: {np.sum(high_temp_days)} days")
print("Specifically:", np.array(days)[high_temp_days])

Output:

Weekly temperature data:
Monday: 22°C
Tuesday: 25°C
Wednesday: 28°C
Thursday: 30°C
Friday: 27°C
Saturday: 24°C
Sunday: 21°C

Average temperature: 25.3°C
Maximum temperature: 30°C
Minimum temperature: 21°C
Temperature range: 9°C
Standard deviation: 3.20°C

Days above average: 3 days
Specifically: ['Wednesday' 'Thursday' 'Friday']

Common Errors and Considerations

1. Import Alias

python
# Correct import
import numpy as np

# Avoid this
from numpy import *  # Pollutes namespace

2. Array Dimensions

python
# Note array dimensions
array_1d = np.array([1, 2, 3])        # Shape: (3,)
array_2d = np.array([[1, 2, 3]])      # Shape: (1, 3)

print(array_1d.shape)  # (3,)
print(array_2d.shape)  # (1, 3)

3. Data Types

python
# Integer division may cause precision loss
array_int = np.array([1, 2, 3])
result = array_int / 2
print(result)  # [0.5 1.  1.5] - Automatically converted to float

# Specify data type
array_float = np.array([1, 2, 3], dtype=np.float64)

Chapter Summary

In this chapter, we learned:

  • How to create our first NumPy program
  • Basic array creation methods
  • Basic array properties and operations
  • Array indexing and slicing
  • Basic mathematical operations and functions
  • Practical application examples
  • Common errors and considerations

Next Steps

In the next chapter, we'll dive deeper into NumPy's fundamental concepts, including array internal structure, memory layout, and more advanced topics.

Exercises

  1. Create an array containing numbers 1 to 20, calculate its squares and cubes
  2. Create a 3x3 random array, find the positions of maximum and minimum values
  3. Create two arrays and calculate their dot product
  4. Simulate rolling a die 1000 times, count the frequency of each outcome
  5. Create a temperature conversion program that converts Celsius to Fahrenheit

Content is for learning and research only.