Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to use the empty() method in NumPy

Harsh Jain

What empty() method does

The empty() method one of the methods you can use to create a NumPy array. However, the difference between this method and the other methods that are used to create an array, is the empty() function creates an uninitialized arrayan array containing random values of specified shape and data type.

What parameters does empty() accept?

The empty() function accepts three parameters:

  • shape: This specifies the shape of the array that you want to create. This value could be an int, like 2, or a tuple of int, like (2, 3).

  • dtype: This is an optional parameter that specifies the data type of your array. By default, its value is float.

  • order: This is also an optional parameter. It specifies how you want to store elements in a multi-dimensional array. It can have two values:

    • C’: This denotes that you want to store the elements in a row-major format.
    • F’: This denotes that you want to store the elements in a column-major format.

    By default, the value of this parameter is ‘C’.

What does empty() return?

The empty() function return an n-dimensional array.

How to use empty() function

Take a look at the code snippet below and use the empty() function.

import numpy as np

one_darray = np.empty(3)
print(one_darray)

two_darray = np.empty([3,3])
print(two_darray)

two_darray_int = np.empty([3,3], dtype=int)
print(two_darray_int)
Use empty() function to create a NumPy array

Explanation:

  • On line 1, we imported the required package.
  • On line 3, we create a 1-D NumPy array (we only specify the shape of the array). It will create an array containing float valuesdefault value for the dtype parameter.
  • On line 6, we create a 2-D NumPy array (we only specify the shape of the array). It will create an array containing float valuesdefault value for the dtype parameter.
  • On line 9, we create a 2-D NumPy array (we specify the shape of the array as well as the data type for the array.) It will create an array containing int valueswe specified the value for the dtype parameter.

So, this is how you can create an uninitializedarray containing random values NumPy array.

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring