NumPy: numpy.asanyarray() function
The numpy.asanyarray() function is used to convert the input to an ndarray, but pass ndarray subclasses through.
numpy.asanyarray(a, dtype=None, order=None)
|a||Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and ndarrays.||Required|
|dtype||By default, the data-type is inferred from the input data.||optional|
|order||Whether to use row-major (C-style) or column-major (Fortran-style) memory representation. Defaults to 'C'.||optional|
Array interpretation of a. No copy is performed if the input is already an ndarray with matching dtype and order. If a is a subclass of ndarray, a base class ndarray is returned.
Example: Convert a list to a numpy array using asanyarray()
>>> import numpy as np >>> a = [2, 4] >>> np.asanyarray(a) array([2, 4])
In the above code the input a is a Python list and not a NumPy array, asanyarray() creates a new NumPy array of dtype int64 by default to represent the elements of the input list. The resulting NumPy array can be used for further mathematical computations and operations.
Example: np.asanyarray() with NumPy recarrays
>>> import numpy as np >>> a = np.array([(2.0, 3), (3.0, 5)], dtype='f4,i4').view(np.recarray) >>> np.asanyarray(a) is a True
In the above code, first, a NumPy record array 'a' is created using the np.array() function and the view() method to convert a structured array to a record array. Then, the np.asanyarray() function is used to return 'a' as an array object. Finally, the code uses the 'is' operator to compare if the returned array object is the same as the original record array a. The code returns True indicating that the returned array object is the same as the original record array.
Python - NumPy Code Editor:
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook