NumPy Creating Arrays from Existing Arrays
In this chapter, we will learn how to create arrays from existing arrays.
numpy.asarray
numpy.asarray is similar to numpy.array, but numpy.asarray has only three parameters, two fewer than numpy.array.
numpy.asarray(a, dtype = None, order = None)
Parameter description:
| Parameter | Description |
|---|---|
| a | Input parameters in any form, can be lists, tuples of lists, tuples, tuples of tuples, lists of tuples, multi-dimensional arrays |
| dtype | Data type, optional |
| order | Optional, with "C" and "F" two options, representing row-major and column-major, the order in which elements are stored in computer memory. |
Example
Convert a list to ndarray:
Example
The output result is:
[1 2 3]
Convert a tuple to ndarray:
Example
The output result is:
[1 2 3]
Convert a list of tuples to ndarray:
Example
The output result is:
[(1, 2, 3) (4, 5)]
Set the dtype parameter:
Example
The output result is:
[ 1. 2. 3.]
numpy.frombuffer
numpy.frombuffer is used to implement dynamic arrays.
numpy.frombuffer accepts a buffer input parameter, reads it in as a stream and converts it into an ndarray object.
numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)
Note:When buffer is a string, Python3 defaults str to Unicode type, so it needs to be converted to bytestring by adding b before the original str.
Parameter description:
| Parameter | Description |
|---|---|
| buffer | Can be any object, will be read in as a stream. |
| dtype | Data type of the returned array, optional |
| count | Number of data items to read, default is -1, reads all data. |
| offset | Starting position for reading, default is 0. |
Python3.x Example
The output result is:
[b'H' b'e' b'l' b'l' b'o' b' ' b'W' b'o' b'r' b'l' b'd']
Python2.x Example
The output result is:
['H' 'e' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd']
numpy.fromiter
The numpy.fromiter method creates an ndarray object from an iterable object and returns a one-dimensional array.
numpy.fromiter(iterable, dtype, count=-1)
| Parameter | Description |
|---|---|
| iterable | Iterable object |
| dtype | Data type of the returned array |
| count | Number of data items to read, default is -1, reads all data |
Example
The output result is:
[0. 1. 2. 3. 4.]Other extensions