w3resource

NumPy Array manipulation: require() function

numpy.require() function

The require() function returns an ndarray of the provided type that satisfies requirements.
This function is useful to be sure that an array with the correct flags is returned for passing to compiled code (perhaps through ctypes).

Syntax:

numpy.require(a, dtype=None, requirements=None)

Version: 1.15.0

Parameter:

Name Description Required /
Optional
a The object to be converted to a type-and-requirement-satisfying array. Required
dtype The required data-type. If None preserve the current dtype. If your application requires the data to be in native byteorder, include a byteorder specification as a part of the dtype specification. Required
requirements The requirements list can be any of the following
  • 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array
  • 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array
  • 'ALIGNED' ('A') - ensure a data-type aligned array
  • 'WRITEABLE' ('W') - ensure a writable array
  • 'OWNDATA' ('O') - ensure an array that owns its own data
  • 'ENSUREARRAY', ('E') - ensure a base array, instead of a subclass
Required

Return value:

out : ndarray - Array interpretation of a. No copy is performed if the input is already an ndarray. If a is a subclass of ndarray, a base class ndarray is returned.

Raises: ValueError - Raises ValueError if a contains NaN (Not a Number) or Inf (Infinity).

Example-1: numpy.require() function

>>> import numpy as np
>>> a = np.arange(9).reshape(3,3)
>>> a.flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False

Example-2: numpy.require() function

>>> import numpy as np
>>> b = np.require(a, dtype=np.float32, requirements=['A', 'O', 'W', 'F'])
>>> b.flags
  C_CONTIGUOUS : False
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False

Python - NumPy Code Editor:

Previous: asscalar()
Next: Joining arrays concatenate()