Different Ways to Create Numpy Arrays in Python
NumPy provides multiple efficient methods for creating arrays, each suited to different use cases and data
sources. This article covers the most commonly used techniques for creating NumPy arrays, along with when
and why to use each method.
Create Numpy Arrays Using Lists or Tuples
The simplest way to create a NumPy array is by passing a Python list or tuple to the [Link]() function.
This method creates a one-dimensional array.
Output
Simple NumPy Array: [1 2 3 4 5]
1/5
Initialize a Python NumPy Array Using Special Functions
NumPy provides several built-in functions to generate arrays with specific properties.
[Link]() : Creates an array filled with zeros.
[Link]() : Creates an array filled with ones.
[Link](): Creates an array filled with a specified value.
[Link]() : Creates an array with values that are evenly spaced within a given range.
[Link]() : Creates an array with values that are evenly spaced over a specified interval.
print("Constant Array:","\n",af)
print("Linspace Array:","\n",la)
Output
Zero Array:
[[0. 0. 0.]
[0. 0. 0.]]
2/5
Ones Array:
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
Constant Array:
[[7 7]
[7 7]]
Range Array:
[0 2 4 6 8]
Linspace Array:
[0. 0.25 0.5 0.75 1. ]
Create Python Numpy Arrays Using Random Number Generation
NumPy provides functions to create arrays filled with random numbers.
[Link]() : Creates an array of specified shape and fills it with random values sampled from a
uniform distribution over [0, 1).
[Link]() : Creates an array of specified shape and fills it with random values sampled from a
standard normal distribution.
[Link]() : Creates an array of specified shape and fills it with random integers within a given
range.
print(ar)
print(an)
3/5
print(ai)
Output
[[0.20421896 0.03530146 0.24261146]
[0.88545223 0.64030701 0.1138876 ]]
[[-0.32144036 -1.62570762]
[-0.80204074 -1.00453878]]
[[2 7 6]
[8 3 9]]
Create Python Numpy Arrays Using Matrix Creation Routines
NumPy provides functions to create specific types of matrices.
[Link]() : Creates an identity matrix of specified size.
[Link]() : Constructs a diagonal array.
np.zeros_like() : Creates an array of zeros with the same shape and type as a given array.
np.ones_like() : Creates an array of ones with the same shape and type as a given array.
print(im)
print(da)
4/5
print(a0)
print(a1)
Output
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
[[1 0 0]
[0 2 0]
[0 0 3]]
[[0 0 0]
[0 0 0]
[0 0 0]]
[[1 1 1]
[1 1 1]
[1 1 1]]
5/5
Mathematical Function - NumPy
NumPy contains a large number of various mathematical operations. NumPy provides standard trigonometric
functions, functions for arithmetic operations, handling complex numbers, etc.
Trigonometric Functions
NumPy provides functions like sin(), cos() and tan() to compute trigonometric ratios element-wise for angles in
radians.
FUNCTION DESCRIPTION
sin( ) Computes sine element-wise
cos( ) Computes cosine element-wise
tan( ) Compute tangent element-wise.
arcsin( ) Inverse sine, element-wise.
1/10
FUNCTION DESCRIPTION
arccos( ) Trigonometric inverse cosine, element-wise.
arctan( ) Trigonometric inverse tangent, element-wise.
arctan2( ) Element-wise arc tangent of x1/x2 choosing the quadrant correctly.
degrees( ) Convert angles from radians to degrees.
rad2deg( ) Convert angles from radians to degrees.
deg2rad Convert angles from degrees to radians.
radians( ) Convert angles from degrees to radians.
hypot( ) Given the “legs” of a right triangle, return its hypotenuse.
unwrap( ) Unwrap by changing deltas between values to 2*pi complement.
Sine Function
The sine function returns the y-coordinate of a point on the unit circle for a given angle (in radians).
2/10
arr = [0, [Link]/2, [Link]/3, [Link]]
s1 = [Link](arr)
print("Sine values:\n", s1)
Output
Sine values:
[0.00000000e+00 1.00000000e+00 8.66025404e-01 1.22464680e-16]
Explanation:
arr stores angles in radians.
[Link]( arr) : calculates sine for each angle element-wise.
Cosine Function
The cosine function returns the x-coordinate of a point on the unit circle for a given angle (in radians).
Output
Cosine values:
[ 1.000000e+00 6.123234e-17 5.000000e-01 -1.000000e+00]
3/10
Explanation: [Link]( arr) : computes cosine values element-wise for all angles.
Hyperbolic Functions
Used to calculate hyperbolic sine, cosine, and tangent.
FUNCTION DESCRIPTION
sinh( ) Hyperbolic sine
cosh( ) Hyperbolic cosine
tanh( ) Compute hyperbolic tangent element-wise.
arcsinh( ) Inverse hyperbolic sine element-wise.
arccosh( ) Inverse hyperbolic cosine, element-wise.
arctanh( ) Inverse hyperbolic tangent element-wise.
Hyperbolic Sine
The hyperbolic sine (sinh) function returns the value of the hyperbola-based analogue of the sine function,
defined as (e^x-e^(-x))/2.
4/10
sh = [Link](arr)
print("Hyperbolic sine values:\n", sh)
Output
Hyperbolic sine values:
[ 0. 2.3012989 1.24936705 11.54873936]
Explanation: [Link]( arr) computes the hyperbolic sine for each value element-wise.
Rounding Functions
Used to round numbers to the nearest integer or specified decimals.
FUNCTION DESCRIPTION
rint( ) Round to nearest integer towards zero.
fix( ) Round to nearest integer towards zero.
floor( ) Return the floor of the input, element-wise.
ceil( ) Return the ceiling of the input, element-wise.
trunc( ) Return the truncated value of the input, element-wise.
5/10
rint( ) Function
[Link]() rounds each element in an array to the nearest integer, returning a new array with the rounded values.
Output
[ 1. 3. -3. -5.]
Exponents and logarithms Functions
NumPy supports exponential, logarithmic, and power operations element-wise.
FUNCTION DESCRIPTION
[Link]( ) e^x element-wise
expm1( ) Calculate exp(x) – 1 for all elements in the array.
exp2( ) Calculate 2**p for all p in the input array.
log10( ) Return the base 10 logarithm of the input array, element-wise.
6/10
FUNCTION DESCRIPTION
log2( ) Base-2 logarithm of x.
log1p( ) Return the natural logarithm of one plus the input array, element-wise.
logaddexp( ) Logarithm of the sum of exponentiations of the inputs.
logaddexp2( ) Logarithm of the sum of exponentiations of the inputs in base-2.
Exponential
[Link]() function calculates e^x for each element in an array, where e is approximately equal to 2.718 is the
base of natural logarithms.
Output
[ 2.71828183 20.08553692 148.4131591 ]
Natural Logarithm
7/10
The natural logarithm ([Link]) computes the logarithm of each element in the array with base e. where 'e' is
approximately equal to 2.718.
Output
[0. 1.09861229 1.60943791 5.54517744]
Arithmetic Functions
Arithmetic functions perform basic mathematical operations in Python, such as addition, subtraction,
multiplication, and division etc.
FUNCTION DESCRIPTION
add( ) Add arguments element-wise.
positive( ) Numerical positive, element-wise.
negative( ) Numerical negative, element-wise.
multiply( ) Multiply arguments element-wise.
8/10
FUNCTION DESCRIPTION
power( ) First array elements raised to powers from second array, element-wise.
subtract( ) Subtract arguments, element-wise.
true_divide( ) Returns a true division of the inputs, element-wise.
floor_divide( ) Return the largest integer smaller or equal to the division of the inputs.
float_power( ) First array elements raised to powers from second array, element-wise.
mod( ) Return the element-wise remainder of division.
remainder( ) Return element-wise remainder of division.
divmod( ) Return element-wise quotient and remainder simultaneously.
reciprocal( ) Returns the reciprocal (1/x) of each element in an array.
divide( ) performs element-wise division between arrays or numbers.
Reciprocal Function
[Link]() computes the reciprocal (1/x) of each element in the input array element-wise.
9/10
Output
0.5
Divide Function
[Link](arr1, arr2) performs element-wise division of the first array by the second array.
print([Link](arr1, arr2))
Output
[1. 9. 0.5 4.2 3.83333333]
10/10
NumPy Array Broadcasting
Broadcasting in NumPy allows us to perform arithmetic operations on arrays of different shapes without
reshaping them. It automatically adjusts the smaller array to match the larger array's shape by replicating its
values along the necessary dimensions. This makes element-wise operations more efficient by reducing
memory usage and eliminating the need for loops.
Lets see an example:
import numpy as np
a = [Link]([[1, 2, 3], [4, 5, 6]])
x = 10
print(a + x)
Output
[[11 12 13]
[14 15 16]]
Explanation:
NumPy expands the scalar x to match the shape of array a.
The operation a + x adds 10 to each element of a.
Working of Broadcasting in NumPy
Broadcasting applies specific rules to find whether two arrays can be aligned for operations or not that are:
1. Check Dimensions: Ensure the arrays have the same number of dimensions or expandable dimensions.
2. Dimension Padding: If arrays have different numbers of dimensions the smaller array is left-padded with
ones.
3. Shape Compatibility: Two dimensions are compatible if they are equal or one of them is 1.
If these conditions aren’t met NumPy will raise a ValueError. Lets see various examples for broadcasting below:
Example 1: Broadcasting a Scalar to a 1D Array
It creates a NumPy array arr with values [1, 2, 3] and adds a scalar value 1 to each element of the array using
broadcasting.
Output
[2 3 4]
Example 2: Broadcasting a 1D Array to a 2D Array
This example shows how a 1D array a1 is added to a 2D array a2. NumPy automatically expands the 1D array
along the rows of the 2D array to perform element-wise addition.
Output
[[ 3 7 11]
Explanation:
a1 has shape (3,) and a2 has shape (2, 3).
NumPy automatically repeats a1 across both rows of a2 so their shapes match.
Then it adds elements position-wise: [1, 3, 5] + [2, 4, 6] = [3, 7, 11] and [7, 9, 11] + [2, 4, 6] = [9, 13, 17]
Example 3: Broadcasting in Conditional Operations
This example checks each age in the array and assigns "Adult" or "Minor" using [Link]().
Output
['Minor' 'Adult' 'Adult' 'Adult' 'Adult' 'Adult']
Explanation:
ages > 18 creates a Boolean array by checking every value at once (broadcasting).
[Link]() picks "Adult" for True and "Minor" for False without any loop.
The result is an array labeling each age correctly.
Example 4: Using Broadcasting for Matrix Multiplication
In this example, each element of a 2D matrix is multiplied by the corresponding element in a broadcasted
vector.
Output
[[10 40]
[30 80]]
Explanation:
The vector v is broadcast across each row of m.
Multiplication happens element-wise without loops.
Result is a scaled version of the matrix.
Example 5: Scaling Data with Broadcasting
Consider a real-world scenario where we need to calculate the total calories in foods based on the amount of
fats, proteins and carbohydrates. Each nutrient has a specific caloric value per gram.
Fats: 9 calories per gram (CPG)
Proteins: 4 CPG
Carbohydrates: 4 CPG
Scaling Data with Broadcasting
Left table shows the original data with food items and their respective grams of fats, proteins and carbs. The
array [9, 4, 4] represents the caloric values per gram for fats, proteins and carbs respectively. This array is
being broadcast to match the dimensions of the original data and arrow indicates the broadcasting operation.
Broadcasting array is multiplied element-wise with each row of the original data.
As a result right table shows the result of the multiplication where each cell represents the caloric
contribution of that specific nutrient in the food item.
[55.2, 31.7, 23.9],
[14.4, 11.0, 4.9] ])
cpg = [Link]([9, 4, 4])
res = fd * cpg
print(res)
Output
[[ 7.2 11.6 15.6]
[471.6 94.4 146. ]
[496.8 126.8 95.6]
[129.6 44. 19.6]]
Explanation:
cpg (9, 4, 4) broadcasts across each row of fd.
Each nutrient gram is multiplied by its calorie value.
Result is a matrix showing calorie contribution from fats, proteins and carbs for each food item.
Example 6: Adjusting Temperature Data Across Multiple Locations
Suppose you have a 2D array representing daily temperature readings across multiple cities and you want to
apply a correction factor to each city’s temperature data.
temp = [Link]([ [30, 32, 34, 33, 31],
[25, 27, 29, 28, 26],
[20, 22, 24, 23, 21] ])
corr = [Link]([1.5, -0.5, 2.0])
res = temp + corr[:, None]
print(res)
Output
[[31.5 33.5 35.5 34.5 32.5]
[24.5 26.5 28.5 27.5 25.5]
[22. 24. 26. 25. 23. ]]
Explanation:
corr[:, None] turns the 1D array into a column vector.
NumPy broadcasts this vector down each row of temp.
Each city’s temperatures get adjusted using its corresponding correction factor.
Example 7: Normalizing Image Data
Normalization is important in many real-world scenarios like image processing and machine learning because
it:
1. Centers data by subtracting the mean by ensuring features have zero mean.
2. Scales data by dividing by the standard deviation by ensuring features have unit variance.
3. Improves numerical stability and performance of algorithms like gradient descent.
Let's see how broadcasting simplifies normalization:
Output
[[ 1.22474487 1.22474487 0. ]
[ 0. 0. 1.22474487]
[-1.22474487 -1.22474487 -1.22474487]]
Explanation:
m and s are 1D arrays (mean and std for each column).
NumPy broadcasts them across all rows of img.
(img - m) centers the data.
Dividing by s scales it, giving the normalized values.
Example 8: Centering Data in Machine Learning
Centering data is an important step in many machine learning workflows. Broadcasting helps center the data
efficiently by subtracting the mean from each feature. This example centers each feature by subtracting its
mean using NumPy broadcasting.
data = [Link]([ [10, 20],
[15, 25],
[20, 30] ])
Output
[[-5. -5.]
[ 0. 0.]
[ 5. 5.]]
Explanation:
m is a 1D array containing the mean of each column.
NumPy broadcasts m across all rows.
Subtracting it centers every feature around zero.