You are currently viewing Ways to Create NumPy Array with Examples

There are various ways to create or initialize arrays in NumPy, one most used approach is using numpy.array() function. This method takes the list of values or a tuple as an argument and returns a ndarray object (NumPy array).In Python, matrix-like data structures are most commonly used with numpy arrays.

Advertisements

The numpy Python package is well-developed for efficient computation of matrices. N-dimensional arrays play a major role in machine learning and data science. In order to use NumPy arrays, we have to initialize or create NumPy arrays. In this article, I will explain how to create NumPy arrays in different ways with examples.

Following are quick examples of ways to create NumPy array.


# Import numpy module
import numpy as np

# Example 1: Creation of 1D array
arr1=np.array([10,20,30])
print("My 1D array:\n",arr1)

# Example 2: Create a 2D numpy array
arr2 = np.array([[10,20,30],[40,50,60]])
print("My 2D numpy array:\n", arr2)

# Example 3: Create a sequence of integers
# from 0 to 20 with steps of 3
arr= np.arange(0, 20, 3)
print ("A sequential array with steps of 3:\n", arr)

# Example 4: Create a sequence of 5 values in range 0 to 3
arr= np.linspace(0, 3, 5)
print ("A sequential array with 5 values between 0 and 5:\n", arr)

# Example 5: Use asarray() convert array
list = [20,40,60,80]
array = np.asarray(list)
print(" Array:", array)

# Example 6: Use empty() create array
arr = (3, 4)  # 3 rows and 4 columns
rr1 = np.empty(arr)
print(" Array with values:\n",arr1)

# Example 7:Use zero() create array
arr = np.zeros((3,2))
print("numpy array:\n", arr)
print("Type:", type(arr))

# Example 8: Use ones() create array
arr = np.ones((2,3))
print("numpy array:\n", arr)
print("Type:", type(arr))

# Create array from existing array
# Using copy()
arr=np.array([10,20,30])
arr1=arr.copy()
print("Original array",arr)
print("Copied array",arr1)

# Create array using = operator
arr=np.array([10,20,30])
arr1=arr
print("Original array",arr)
print("Copied array",arr1)

1. Create NumPy Array

NumPy arrays support N-dimensional arrays, let’s see how to initialize single and multi-dimensional arrays using numpy.array() function. This function returns ndarray object.


# Syntax of numpy.array()
numpy.array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, like=None)

1.1. Create a Single Dimension NumPy Array

You can create a single-dimensional array using a list of numbers. Use numpy.array() function which is the most familiar way to create a NumPy array from other array-like objects. For example, you can use this function to create an array from a Python list and tuple.


# Import numpy module
import numpy as np

# Creation of 1D array
arr1=np.array([10,20,30])
print("Original 1D array:\n",arr1)
print("Type:\n", type(arr1))

Yields below output.

NumPy array create

1.2. Create Multi-Dimensional NumPy Array.

A list of lists will create a 2D Numpy array, similarly, you can also create N-dimensional arrays. Let’s create a 2D array by using numpy.array() function.


# Create a 2D numpy array
arr2 = np.array([[10,20,30],[40,50,60]])
print("My 2D numpy array:\n", arr2)
print("Type:", type(arr2))

Yields below output.

NumPy array create

2. Use arange() Function to Create an Array

To create an array with sequences of numbers, NumPy provides the arange() function which is analogous to the Python built-in range() but returns an array. Following is the syntax of arange().


# Syntax of arange()
numpy.arange([start, ]stop, [step, ]dtype=None, *, like=None)

This function returns evenly spaced values within a given interval. In other words, this returns a list of values from start and stop value by incrementing 1. If step is specified, it increments the value by a given step. For example, np.arange(0, 10, 3) returns [0,3,6,9].


# Create a sequence of integers
# From 0 to 20 with step of 3
arr= np.arange(0, 20, 3)
print ("A sequential array with steps of 3:\n", arr)

# Output:
# A sequential array with steps of 3:
# [ 0  3  6  9 12 15 18]

3. Using linspace() Function

linspace() returns evenly spaced values within a given interval. Like arange() function, linspace() function can also be used to create a NumPy array but with more discipline.

In this function, we have control over where to start the Numpy array, where to stop, and the number of values to return between the start and stop. Imagine if you have some arguments in arange() function to generate a Numpy array, which gives you the output array that has elements not linearly stepped, in such a case, linspace() comes to the rescue.


# Syntax of linspace()
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)

This function takes arguments start, stop and num (the number of elements) to be outputted. These number of elements would be linearly spaced in the range mentioned. For example,


# Create a sequence of 3 values in range 0 to 20
arr= np.linspace(0, 20, 3)
print(arr)

# Output:
# [ 0. 10. 20.]

4. Creation of NumPy Array From list/tuple Using asarray()

As I explained above, arrays can also be created with the use of various data types such as lists, tuples, etc. Lists can convert to arrays using the below built-in functions in the Python NumPy library.

  • numpy.array()
  • numpy.asarray()

Usage of numpy.array() I have already covered it in section 1, now let’s see how to use numpy.asarray() and the difference with array(). Actually numpy.asarray() function calls the numpy.array() function internally.


# Syntax of asarray()
def asarray(a, dtype=None, order=None):
    return array(a, dtype, copy=False, order=order)

The other difference between np.array() and np.asarray() is that, the copy flag is false with np.asarray(), and true (by default) in the case of np.array().

This means that np.array() will make a copy of the object (by default) and convert that to an array. For example,


# Use asarray() convert array
list = [20,40,60,80]
array = np.asarray(list)
print("Array:", array)

# Output:
# Array: [20 40 60 80]

5. Create Empty Array using empty() Function:

Even if you don’t have any values to create a NumPy array, you can still create an array that is empty. Actually, an empty array isn’t empty, it just contains very small, meaningless values.

Use numpy.empty() function to create an empty NumPy array, pass it a shape tuple. The code below demonstrates how this is done. Note that the output array does contain values.


# Syntax of the empty function
empty(shape, dtype)

Let’s see with an example. In the below, it creates an empty array with shape 3 rows and 4 columns.


# Use empty() create array
arr = (3, 4)  # 3 rows and 4 columns
rr1 = np.empty(arr)
print(" Array with values:\n",arr1)

# Output:
# Array with values:
# [[6.23042070e-307 4.67296746e-307 1.69121096e-306 4.89531867e-307]
# [4.45038199e-307 7.56587584e-307 1.37961302e-306 1.05699242e-307]
# [8.01097889e-307 9.79103798e-307 8.01097889e-307 2.56765117e-312]]

6. Creation of NumPy Array of Zeros

Use the zeros() function to create an array of a specified shape that is filled with the value zero (0). The zeros() function is nearly the same as ones() and empty(), the only difference is that the resulting array is filled with the value of zero. Once again, you just need to pass a shape tuple to this function.


# Use zeros() create an array
arr = np.zeros((3,2))
print("numpy array:\n", arr)

# Output:
# numpy array:
# [[0. 0.]
# [0. 0.]
# [0. 0.]]

7. Creation of NumPy Array with Value One’s

To create a NumPy array of the desired shapes filled with ones using the numpy.ones() function. For Example,


# Use ones() create an array
arr = np.ones((2,3))
print("numpy array:\n", arr)

# Output:
# numpy array:
# [[1. 1. 1.]
# [1. 1. 1.]]

8. Create Array from Existing Array

We can create an array from an existing array by copying array elements into the other array.

8.1 Using copy() Method

To create an array from an existing NumPy array Python provides an in-built method that is the copy() method. In simpler words to copy the array elements into another array. If you make changes in an original array that will not be reflected in a copy method. Below is the syntax of the copy().


# Syntax of copy()
arr1=arr.copy()

copy() method returns a new array, which contains exactly the same elements as original array. For example,


# Create array from existing array
# Using copy()
arr=np.array([10,20,30])
arr1=arr.copy()
print("Original array",arr)
print("Copied array",arr1)

# Output:
# Original array [10 20 30]
# Copied array [10 20 30]

If you allow any changes in the original array that changes are not reflected in the original array.


# Modifying array
arr=np.array([10,20,30])
arr1=arr.copy()
arr[0]=40
print("Original array",arr)
print("Copied array",arr1)

# Output:
# Original array [40 20 30]
# Copied array [10 20 30]

8.2 Using = (assignment operator)

Use = (assign operator) to copy the elements of the array into the another array. It is not only copies the elements but also assigns them as equals. see the below examples. If any modifications are allowed in the original array which will be reflected in the copy array. For example,


# Create array using = operator
arr=np.array([10,20,30])
arr1=arr
print("Original array",arr)
print("Copied array",arr1)

# Output:
Original array [10 20 30]
Copied array [10 20 30]

# Modify the array
arr=np.array([10,20,30])
arr[1]=40
arr1=arr
print("Original array",arr)
print("Copied array",arr1)

# Output:
# Original array [10 40 30]
# Copied array [10 40 30]

9. Create NumPy Array from a CSV File

CSV file format is the easiest and most useful format for storing the data. Let’s see how to create a NumPy array by reading a CSV file. First, let’s create a CSV file with the below content and save it as file.csv.

create numpy array

In the below example replace the <path> with the actual path where you saved the CSV file.


path = open('<path>/file.csv')
array = np.loadtxt(path, delimiter=",",dtype='int')
print(array)

# Outputs:
# [[1 2 3 4]
# [5 6 7 8]]

Frequently Asked Questions

How can I create a NumPy array from a Python list or tuple?

You can create a NumPy array from a Python list or tuple using the np.array() function provided by the NumPy library.

How can I create an array with a range of values using NumPy?

You can create an array with a range of values using the np.arange() function in NumPy. The np.arange() function creates an array with evenly spaced values within a specified interval.

What is the np.linspace() function used for?

The np.linspace() function is used to create an array of evenly spaced values over a specified range. It is particularly useful when you need to generate a set of values for a function within a specific interval.

How can I create arrays filled with zeros or ones using NumPy?

You can create arrays filled with zeros or ones in NumPy using the np.zeros() and np.ones() functions.

Can I create NumPy arrays using custom functions?

You can create NumPy arrays using custom functions with the np.fromfunction() function provided by NumPy. np.fromfunction() constructs an array by executing a function over each coordinate of the array.

How can I create arrays with random values using NumPy?

You can create arrays with random values using various functions provided by the np.random module.

Conclusion

In this article, I have explained how to create a NumPy array in different ways with examples. also learned how to initialize a Numpy array by reading content from a CSV file.

Happy learning !!

Related Articles

References

Naveen Nelamali

Naveen Nelamali (NNK) is a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, He has honed his expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. Naveen journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. In this blog, he shares his experiences with the data as he come across. Follow Naveen @ LinkedIn and Medium