NumPy Basics explained for beginners with practical Python examples. Start learning numerical computing for data science and AI today.
NumPy is one of the most powerful and essential Python libraries for numerical computing and data analysis. If you want to work in data science, machine learning, artificial intelligence, scientific computing, or even web analytics, learning NumPy Basics is the first major step.
In this complete guide, you will learn:
- What NumPy is
- Why NumPy is important
- How arrays work
- Array creation methods
- Indexing and slicing
- Mathematical operations
- Statistical functions
- Reshaping arrays
- Random module
- Real-world examples
By the end of this tutorial, you will have a strong understanding of NumPy basics with practical examples.
- What is NumPy?
- Why Use NumPy?
- Creating Arrays
- NumPy Array Attributes
- Indexing and Slicing
- Array Operations
- Mathematical Functions
- Statistical Functions
- Reshaping Arrays
- Joining and Splitting Arrays
- Iterating Through Arrays
- Random Module in NumPy
- Real-World Examples
- Advantages of NumPy
- Conclusion
- FAQs
What is NumPy?
NumPy stands for Numerical Python. It is an open-source Python library used for:
- Numerical computations
- Working with arrays
- Mathematical operations
- Linear algebra
- Statistical calculations
The main feature of NumPy is the ndarray (N-dimensional array).
Unlike Python lists, NumPy arrays are:
- Faster
- More memory efficient
- Easier for mathematical operations
Why Use NumPy?
Here are the major reasons developers and data scientists use NumPy.
1. Faster Performance
NumPy arrays are optimized and much faster than regular Python lists.
2. Less Memory Usage
Arrays consume less memory compared to lists.
3. Mathematical Operations
You can perform vectorized calculations easily.
4. Used in Data Science
Libraries like:
- Pandas
- TensorFlow
- Scikit-learn
are built on NumPy.
Installing NumPy
Install NumPy using pip:
pip install numpy
You can learn more from the official website:
Importing NumPy
The standard way to import NumPy is:
import numpy as np
Here:
numpy→ library namenp→ alias for shorter code
Example:
import numpy as npprint(np.__version__)
Creating Arrays
1. Creating a 1D Array
import numpy as nparr = np.array([1, 2, 3, 4, 5])print(arr)
Output:
[1 2 3 4 5]
2. Creating a 2D Array
arr2 = np.array([[1, 2, 3], [4, 5, 6]])print(arr2)
Output:
[[1 2 3] [4 5 6]]
3. Creating a 3D Array
arr3 = np.array([ [[1, 2], [3, 4]], [[5, 6], [7, 8]]])print(arr3)
NumPy Array Attributes
NumPy arrays have useful properties.
Shape
Shows rows and columns.
arr = np.array([[1, 2, 3], [4, 5, 6]])print(arr.shape)
Output:
(2, 3)
Dimensions
print(arr.ndim)
Output:
2
Size
print(arr.size)
Output:
6
Data Type
print(arr.dtype)
Output:
int64
Special Array Creation Functions
Zeros Array
arr = np.zeros((2, 3))print(arr)
Output:
[[0. 0. 0.] [0. 0. 0.]]
Ones Array
arr = np.ones((3, 3))print(arr)
Identity Matrix
arr = np.eye(3)print(arr)
Output:
[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]
Range of Values
arr = np.arange(1, 10, 2)print(arr)
Output:
[1 3 5 7 9]
Linearly Spaced Values
arr = np.linspace(0, 1, 5)print(arr)
Output:
[0. 0.25 0.5 0.75 1. ]
Indexing and Slicing
Accessing Elements
arr = np.array([10, 20, 30, 40])print(arr[0])print(arr[2])
Output:
1030
Negative Indexing
print(arr[-1])
Output:
40
Slicing Arrays
print(arr[1:3])
Output:
[20 30]
2D Array Indexing
arr = np.array([[1, 2, 3], [4, 5, 6]])print(arr[0, 1])
Output:
2
Array Operations
NumPy allows element-wise operations.
Addition
a = np.array([1, 2, 3])b = np.array([4, 5, 6])print(a + b)
Output:
[5 7 9]
Subtraction
print(a - b)
Multiplication
print(a * b)
Output:
[ 4 10 18]
Division
print(a / b)
Mathematical Functions
NumPy contains many mathematical functions.
Square Root
arr = np.array([1, 4, 9, 16])print(np.sqrt(arr))
Output:
[1. 2. 3. 4.]
Power
print(np.power(arr, 2))
Absolute Values
arr = np.array([-1, -5, 10])print(np.abs(arr))
Trigonometric Functions
arr = np.array([0, np.pi/2, np.pi])print(np.sin(arr))
Statistical Functions
NumPy is very useful for statistics.
Mean
arr = np.array([1, 2, 3, 4, 5])print(np.mean(arr))
Output:
3.0
Median
print(np.median(arr))
Standard Deviation
print(np.std(arr))
Minimum and Maximum
print(np.min(arr))print(np.max(arr))
Sum
print(np.sum(arr))
Reshaping Arrays
Reshaping changes array dimensions.
Reshape Example
arr = np.array([1, 2, 3, 4, 5, 6])new_arr = arr.reshape(2, 3)print(new_arr)
Output:
[[1 2 3] [4 5 6]]
Flatten Array
print(new_arr.flatten())
Joining Arrays
Concatenate Arrays
a = np.array([1, 2])b = np.array([3, 4])print(np.concatenate((a, b)))
Output:
[1 2 3 4]
Stack Arrays
print(np.vstack((a, b)))
Splitting Arrays
arr = np.array([1, 2, 3, 4, 5, 6])print(np.array_split(arr, 3))
Output:
[array([1, 2]), array([3, 4]), array([5, 6])]
Iterating Through Arrays
Loop Through 1D Array
arr = np.array([1, 2, 3])for x in arr: print(x)
Loop Through 2D Array
arr = np.array([[1, 2], [3, 4]])for row in arr: for item in row: print(item)
Random Module in NumPy
The random module is widely used in machine learning and simulations.
Random Integer
print(np.random.randint(1, 100))
Random Array
print(np.random.rand(3, 3))
Random Choice
colors = ["red", "blue", "green"]print(np.random.choice(colors))
Real-World Examples
Example 1: Student Marks Analysis
marks = np.array([85, 90, 78, 92, 88])print("Average:", np.mean(marks))print("Highest:", np.max(marks))print("Lowest:", np.min(marks))
Output:
Average: 86.6Highest: 92Lowest: 78
Example 2: Temperature Analysis
temps = np.array([30, 32, 35, 31, 29])print("Average Temperature:", np.mean(temps))
Example 3: Matrix Addition
a = np.array([[1, 2], [3, 4]])b = np.array([[5, 6], [7, 8]])print(a + b)
NumPy vs Python List
| Feature | Python List | NumPy Array |
|---|---|---|
| Speed | Slower | Faster |
| Memory | More | Less |
| Mathematical Operations | Difficult | Easy |
| Data Type | Mixed | Same Type |
| Performance | Low | High |
Advantages of NumPy
High Performance
Optimized for complex calculations.
Multi-Dimensional Arrays
Supports 1D, 2D, and 3D arrays.
Scientific Computing
Widely used in research and AI.
Large Community Support
Extensive tutorials and documentation available.
Common NumPy Functions Cheat Sheet
| Function | Purpose |
|---|---|
np.array() | Create array |
np.zeros() | Create zeros |
np.ones() | Create ones |
np.arange() | Create range |
np.linspace() | Create evenly spaced values |
np.mean() | Calculate mean |
np.sum() | Sum elements |
np.reshape() | Change dimensions |
np.concatenate() | Join arrays |
np.random.rand() | Random numbers |
Best Practices for Beginners
Use Aliases
Always import as:
import numpy as np
Prefer Vectorized Operations
Avoid loops when possible.
Bad:
result = []for i in range(len(arr)): result.append(arr[i] * 2)
Good:
result = arr * 2
Learn Broadcasting
Broadcasting makes calculations easier and faster.
Example:
arr = np.array([1, 2, 3])print(arr + 10)
Output:
[11 12 13]
Conclusion
NumPy is the foundation of numerical computing in Python. Whether you want to become a:
- Data Scientist
- Machine Learning Engineer
- AI Developer
- Python Developer
- Researcher
learning NumPy is essential.
In this tutorial, you learned:
- Array creation
- Indexing and slicing
- Mathematical operations
- Statistical functions
- Reshaping arrays
- Random module
- Real-world examples
The more you practice NumPy, the easier advanced libraries like Pandas and TensorFlow will become.
FAQs
Is NumPy easy for beginners?
Yes. NumPy is beginner-friendly if you know basic Python.
Why is NumPy faster than lists?
NumPy uses optimized C-based implementations internally.
Can NumPy handle large datasets?
Yes. NumPy is designed for high-performance computing.
Is NumPy used in machine learning?
Absolutely. Most machine learning libraries depend on NumPy.
What should I learn after NumPy?
After NumPy, learn:
- Pandas
- Matplotlib
- Scikit-learn
- TensorFlow
These libraries are commonly used in data science and AI development.