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

import numpy as np x = [1,2,3] a = np.asarray(x) print (a)

The output result is:

[1  2  3]

Convert a tuple to ndarray:

Example

import numpy as np x = (1,2,3) a = np.asarray(x) print (a)

The output result is:

[1  2  3]

Convert a list of tuples to ndarray:

Example

import numpy as np x = [(1,2,3),(4,5)] a = np.asarray(x) print (a)

The output result is:

[(1, 2, 3) (4, 5)]

Set the dtype parameter:

Example

import numpy as np x = [1,2,3] a = np.asarray(x, dtype = float) print (a)

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

import numpy as np s = b'Hello World' a = np.frombuffer(s, dtype = 'S1') print (a)

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

import numpy as np s = 'Hello World' a = np.frombuffer(s, dtype = 'S1') print (a)

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

import numpy as np # Use the range function to create a list object list=range(5) it=iter(list) # Use an iterator to create ndarray x=np.fromiter(it, dtype=float) print(x)

The output result is:

[0. 1. 2. 3. 4.]
Other extensions