We can create a NumPy array using various functions provided by the Python NumPy library. This package provides a multidimensional array object and various other required objects, routines, for efficient functionality.
Using numpy.array() Function
We can use the numpy.array() function to create an array by passing a Python list or tuple as an argument to the function. This function converts input data (like lists, tuples, etc.) into an ndarray (NumPy array). Following is the syntax:
Example: Creating a 1D NumPy Array
Output:
Example: Creating a 2D NumPy Array
Output:
Using numpy.zeros() Function
We can also use the numpy.zeros() function for creating an array by specifying the desired shape of the array as a tuple or an integer. This function creates a NumPy array filled with zeros. It accepts the shape of the array as an argument and optionally the data type (dtype). By default, the data type is float64. Following is the syntax:
Example
Output:
Using numpy.ones() Function
On the other hand, the numpy.ones() function creates an array where all elements are set to 1. It accepts three main parameters: shape, dtype, and order.
- shape: defines the dimensions of the array.
- dtype: specifies the desired data type of the array elements (default is float64).
- order: determines the memory layout (C-style or Fortran-style).
Example: Creating 1D array of ones
Output:
Example: Creating 2D array of ones
Output:
Example: Creating a Fortran-ordered array of ones
Output:
Using numpy.arange() Function
The numpy.arange() function creates an array by generating a sequence of numbers based on specified start, stop, and step values. It is similar to Python's built-in range() function.
Example
Output:
Using numpy.linspace() Function
We can even use the numpy.linspace() function to create an array by specifying the start, stop, and the number of elements we want. The array created by this function consists of evenly spaced values over a specified interval.
Example
Output:
Important Difference: linspace() vs arange()
Students often confuse linspace() with arange().
np.arange(0, 20, 2)means: Start at 0, increase by 2. (I specify the STEP)np.linspace(0, 20, 11)means: Start at 0, end at 20, and create exactly 11 evenly spaced values. (I specify the NUMBER OF VALUES)
Real-World Examples of linspace()
1. Solar Power Generation ☀️
Suppose your solar plant generates approximately 0 kW at 6 AM and reaches 20 kW at 12 PM. You want readings at 7 equally spaced time points.
You don't want to manually calculate 0, 3.33, 6.67, 10, etc. Instead,
np.linspace(0, 20, 7) means: Start at 0, end at 20, and give me exactly 7 evenly spaced values.
2. Temperature Monitoring 🌡️
Suppose a machine temperature rises from 30°C to 90°C, and you need 13 sample points for a simulation.
3. Speed of a Car 🚗
A car accelerates from 0 km/h to 120 km/h. You want 9 evenly distributed speed values to simulate fuel consumption or braking performance for each speed.
4. Salary Simulation 💰
Suppose you want to test a tax calculation system for salaries from ₹20,000 to ₹1,00,000, using 9 evenly spaced salary values.
5. Camera / Image Processing 📷
Suppose an image-processing algorithm needs brightness levels from 0 to 255, but you only want 10 test values. This can be useful when testing image filters at different brightness levels.
Classroom Example 🎓
Ask students: A water tank has a capacity of 5000 liters. Create 11 equally spaced water-level values from empty to full.
Using numpy.random.rand() Function
This function is used to create an array of specified shape filled with random values sampled from a uniform distribution over [0, 1).
Example
Using numpy.empty() Function
This function initializes an array without initializing its elements; the content of the array is arbitrary and may vary.
Example
Output:
Using numpy.full() Function
Using the numpy.full() function, we can create an array with a desired shape and set all the elements in it to a specific value.
Example
Output:
Practice Questions ✍️
Q1. Integer Conversion
Create an array: arr = np.array([10, 20, 30, 40])
Create another array where the datatype is explicitly set to float.
Expected Concept: dtype=float
Q2. Integer Size
Create an array [100, 200, 300, 400] with dtype=np.int32.
Then create another with dtype=np.int64.
Compare their dtype attributes.
Q3. Classroom Attendance
Create an array of 10 students, where initially every student is marked as present:
Q4. Matrix Initialization
Create a 3 × 4 matrix containing only 1s.
Expected Output:
Q5. Bank Account Initialization
Create an array for 8 bank accounts, where the initial balance of every account is ₹0.
Q6. Image Processing
Create a 5 × 5 matrix containing zeros.
Think of this as a blank grayscale image.
Q7. Normalized Temperature Readings
Generate 24 random values between 0 and 1 representing normalized temperature readings for 24 hours.
Then, find out the maximum and minimum temperature from the 24 hours.
Q8. Random Student Percentage
Generate 10 random values between 0 and 1 and convert them into percentages between 0 and 100.
Q9. Even Numbers
Create an array of all even numbers between 2 and 50.
Q10. Odd Numbers
Create an array of all odd numbers between 1 and 50.
Q11. Sales Simulation
A shop wants to simulate sales for 30 days.
- Create Day numbers from 1 to 30 using
np.arange(). - Generate random sales values between ₹1,000 and ₹10,000 using
np.random.rand().
Then find:
- Total sales
- Average sales
- Maximum sales
- Minimum sales
Functions Used for Creation of NumPy Arrays
Basic Array Creation
| Functions | Description |
|---|---|
array() | used to create a numpy array |
asarray() | Convert the input to an array |
asanyarray() | Convert the input to an ndarray, but pass ndarray subclasses through |
copy() | Return an array copy of the given object |
Array Creation with Specific Shapes and Data
| Functions | Description |
|---|---|
zeros() | Return a new array of given shape and type, filled with zeros |
ones() | Return a new array of given shape and type, filled with ones |
empty() | Return a new array of given shape and type, without initializing entries |
full() | Return a new array of given shape and type, filled with fill_value |
Array Creation with Sequences
| Functions | Description |
|---|---|
arange() | Return evenly spaced values within a given interval |
linspace() | Return evenly spaced numbers over a specified interval. |
logspace() | Return numbers spaced evenly on a log scale. |
Special Arrays
| Functions | Description |
|---|---|
eye() | Return a 2-D array with ones on the diagonal and zeros in all other positions |
identity() | Return the identity array. |
diag() | Extract a diagonal or construct a diagonal array |
fromfunction() | Construct an array by executing a function over each coordinate |
fromfile() | Construct an array from data in a text or binary file |
Random Arrays
| Functions | Description |
|---|---|
random.rand() | Random values in a given shape |
random.randn() | Return a sample from the standard normal distribution |
random.randint() | Return random integers from low (inclusive) to high (exclusive) |
random.random() | Return random floats in the half-open interval [0.0, 1.0) |
random.choice() | Generates a random sample from a given 1-D array |
Structured Array
| Functions | Description |
|---|---|
zeros_like() | Return an array of zeros with the same shape and type as a given array |
ones_like() | Return an array of ones with the same shape and type as a given array. |
empty_like() | Return a new array with the same shape and type as a given array |
full_like() | Return a full array with the same shape and type as a given array |