Numpy Array Creation

The ndarray object can be constructed by using the following routines.

Numpy.empty

As the name specifies, The empty routine is used to create an uninitialized array of specified shape and data type.

The syntax is given below.

snippet
numpy.empty(shape, dtype = float, order = 'C')

It accepts the following parameters.

  • Shape: The desired shape of the specified array.
  • dtype: The data type of the array items. The default is the float.
  • Order: The default order is the c-style row-major order. It can be set to F for FORTRAN-style column-major order.

Example

snippet
import numpy as np
arr = np.empty((3,2), dtype = int)
print(arr)

Output:

Output
[[ 140482883954664 36917984] [ 140482883954648 140482883954648] [6497921830368665435 172026472699604272]]

NumPy.Zeros

This routine is used to create the numpy array with the specified shape where each numpy array item is initialized to 0.

The syntax is given below.

snippet
numpy.zeros(shape, dtype = float, order = 'C')

It accepts the following parameters.

  • Shape: The desired shape of the specified array.
  • dtype: The data type of the array items. The default is the float.
  • Order: The default order is the c-style row-major order. It can be set to F for FORTRAN-style column-major order.

Example

snippet
import numpy as np
arr = np.zeros((3,2), dtype = int)
print(arr)

Output:

Output
[[0 0] [0 0] [0 0]]

NumPy.ones

This routine is used to create the numpy array with the specified shape where each numpy array item is initialized to 1.

The syntax to use this module is given below.

snippet
numpy.ones(shape, dtype = none, order = 'C')

It accepts the following parameters.

  • Shape: The desired shape of the specified array.
  • dtype: The data type of the array items.
  • Order: The default order is the c-style row-major order. It can be set to F for FORTRAN-style column-major order.

Example

snippet
import numpy as np
arr = np.ones((3,2), dtype = int)
print(arr)

Output:

Output
[[1 1] [1 1] [1 1]]
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +