Numpy n dimensional Arrays ( ndarray )

NumPy (Numerical Python) is a popular open-source Python library used for numerical computing and data analysis. Axis of Two dimensional array

Numpy is used scientific computing with Python.
We can create powerful multidimensional arrays using Numpy.

Uniform Data Type Boosts NumPy Speed & Efficiency

Numpy requires all elements are to be of same data type. ( This is the main difference with Pandas which can accommodate different data types. ) It makes storage more memory-efficient, enables faster access, and dramatically boosts the speed of mathematical operations compared to data structures that store mixed types.

NumPy is often used in combination with other Python libraries, such as Pandas, Matplotlib, and Scikit-learn, to create a complete data analysis ecosystem in Python.

Some of the key features of NumPy :

  1. Fast vectorized operations: NumPy allows you to perform operations on entire arrays rather than looping through each element, which can be much faster.
    import numpy as np
    print(np.array([1, 2, 3]) * 10) # Output [10 20 30]
  2. Broadcasting: NumPy allows you to perform operations between arrays with different shapes and sizes, which makes it easy to perform operations on data that is not the same shape.
  3. import numpy as np
    
    a1 = np.array([2, 4, 6])                # 1D array (shape: (3,))
    a2 = np.array([[1, 3, 5],
                   [7, 9, 11]])             # 2D array (shape: (2,3))
    
    result = a1 + a2
    print(result)
    
    # Output: [[ 3  7 11]
    # [ 9 13 17]]
  4. Linear algebra: NumPy provides a suite of functions for performing linear algebra operations such as matrix multiplication, eigenvalues, and eigenvectors.
  5. import numpy as np
    A = np.array([[1, 2], [3, 4]])
    B = np.array([[5, 6], [7, 8]])
    result = np.dot(A, B)
    print(result)
    
    # Output: [[19 22]
    #          [43 50]]
  6. Random number generation: NumPy includes tools for generating random numbers, which are useful for simulations and statistical analysis.
  7. x = np.random.randint(0, 100, 5)
    print(x) # 1D array of 5 random integers between 0 and 100:

Installing Numpy

Use in your command prompt or the environment you are using .
pip install numpy
After installation you can add this line to import Numpy inside Python program.
import numpy as np
Getting the Numpy version installed in your system.
import numpy as np
print("Numpy Version : ",np.__version__)

Creating Numpy Array

import numpy as np
npr=np.array([4,5,9])  
print(npr) # [4,5,9]

l1=[3,2,8] # List 
npr=np.array(l1) # Using List to create np array
print(npr) # [3,2,8]

Numpy installation and creating array at Colab platform using List Tuple and checking the version

Creating array

NumPy provides a wide variety of functions to create arrays efficiently, whether you need simple arrays filled with zeros or ones, arrays with specific ranges or steps, or more complex multi-dimensional structures like meshgrids and diagonals. These array creation tools lay the foundation for powerful scientific and numerical computing.

createCreating array using Numpy
eyearray with ones and zeros
emptyarray without initializing entries
empty_likearray of same shape and type
fullArray filled with input value
onesarray filled with ones
arangecreating array of fixed steps
linspacecreating array of fixed number
zerosAray filled with zeros
Advancedmeshgrid, diag, tile, and repeat

Array Properties & Manipulation

In NumPy, array properties and manipulation techniques form the backbone of powerful data processing. Key features include appending and inserting elements, examining and modifying the dtype, and utilizing a rich collection of array methods to extract or transform data.

NumPy ArrayScientific computing with Python
appendAdding Data to array at the end
insertAdding Data to array at the given index position
dtypeData types of Numpy array
Array MethodsMethods to get result ( output ) using NumPy
array_split()break the array to get sub-arrays
bincountfrequency of occurrence of elements
whereReturn elements depending on condition check
shapeReturn shape of the array
reshapeChange the array shape and dimension
SlicingIndexing and slicing
VectorizationVectorization Patterns (Benchmarks vs Loops)
Broadcastingarithmetic between arrays
viewsViews vs Copies, Strides & Memory Layout
masksBoolean Masks & Conditional Selection
RandomRandom Generator (PCG64) & Reproducibility
dtypesHandling NaNs & Type Casting
ExerciseCreating different types of array

Random Number Generation

Use NumPy’s modern Generator API to create reproducible random data for simulations, testing, and ML workflows. Seed once, draw at any shape, and combine fast vectorized calls to model uncertainty, bootstrap metrics, or synthesize datasets without relying on slow Python loops.

random.randitRandom integers with lower and upper limits and size
random.randUniform distribution [0,1] of random numbers of given shape & population
random.randnNormal distribution of random numbers of given shape & population
random_sampleContinuous uniform distribution over an interval
Statisticalprobability distribution

Statistical & Mathematical Aggregations

Aggregation functions in NumPy allow you to quickly summarize large arrays into meaningful statistics. Whether you’re calculating totals, averages, or variability, these operations work efficiently across chosen axes, making them essential for data analysis and scientific computing.

sum()Sum of elements, or along the axis
mean()Mean value of elements, or along the axis
max()Maximum value among elements, or along the axis
min()Minimum value among elements, or along the axis
std()Standard deviation along the axis
Axis reductionAxis & Reduction Operations

Linear Algebra and Advanced Features

AlgebraLinear Algebra with np.linalg

File I/O , Interoperability and performance

NumPy integrates seamlessly with other libraries like Pandas, Matplotlib, and Scikit-learn. It also provides efficient tools for file handling, saving and loading arrays, and optimizing performance in memory-heavy workflows, making it a strong foundation for data pipelines and ML applications.

When working with arrays, mistakes in shapes and dimensions are common. Understanding how to detect and debug these errors helps prevent silent bugs and ensures that operations like broadcasting, reductions, and reshaping behave as intended.

file i/osave, load, loadtxt, genfromtxt
InteroperabilityPandas Interoperability Guide
PerformancePerformance Optimization
Machine LearningPipelines (with Pandas, Matplotlib, Scikit-learn)

Error Handling & Debugging

ErrorsCommon Errors & Debugging Shapes


Exercise aBasics of Creating Arrays
math functionsNumpy math functions
Get the list of all functions of Numpy. ( Use dir() )
import numpy as np
print(len(dir(np))) # 532
List of functions
for i in dir(np):
    print(i)

Common Use Cases of NumPy

NumPy is the backbone of scientific and analytical computing in Python. Its fast, vectorized operations and efficient memory management make it indispensable for professionals across data science, research, and engineering domains.

  • Data Science & Machine Learning:
    • Data cleaning and preprocessing with numerical arrays.
    • Feature engineering and normalization of datasets.
    • Representing datasets as NumPy arrays for machine learning models (e.g., input for scikit-learn).
    • Implementing custom ML algorithms and gradient-based optimizations.
  • Scientific Computing:
    • Performing numerical simulations in physics, chemistry, and engineering.
    • Solving systems of linear equations and matrix transformations.
    • Signal and image processing using Fourier transforms.
    • Advanced statistical and probabilistic analysis.
  • Image Processing: Images are commonly represented as 2D or 3D NumPy arrays — where dimensions correspond to height, width, and color channels. This makes array manipulation ideal for tasks like filtering, masking, and feature extraction.
  • Financial Modeling: NumPy simplifies time series analysis, portfolio optimization, and risk assessment through efficient handling of large numerical datasets.

NumPy Tutorial for Beginners — Start Fast with Colab & VS Code #numpy



Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer