Easy Tutorial
❮ Numpy Io Numpy Broadcast ❯

Creating Arrays from Existing Arrays in NumPy

In this section, 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 less than numpy.array.

numpy.asarray(a, dtype=None, order=None)

Parameter Description:

Parameter Description
a Input data in any form such as list, tuple of lists, tuple, tuple of tuples, list of tuples, multi-dimensional array
dtype Optional, data type
order Optional, with "C" and "F" options, representing row-major and column-major order in the storage of elements in computer memory

Example

Convert a list to an ndarray:

import numpy as np

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

Output:

[1 2 3]

Convert a tuple to an ndarray:

import numpy as np

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

Output:

[1 2 3]

Convert a list of tuples to an ndarray:

import numpy as np

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

Output:

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

With dtype parameter:

import numpy as np

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

Output:

[1. 2. 3.]

numpy.frombuffer

numpy.frombuffer is used for dynamic array implementation.

numpy.frombuffer accepts a buffer input parameter and reads it as a stream to convert it into an ndarray object.

numpy.frombuffer(buffer, dtype=float, count=-1, offset=0)

Note: When the buffer is a string, Python3 defaults str to Unicode type, so it needs to be converted to a bytestring by adding 'b' in front of the original str.

Parameter Description:

Parameter Description
buffer Any object that can be read as a stream
dtype Optional, data type of the returned array
count Number of data items to read, default is -1, which means all data
offset Starting position to read, default is 0

Python3.x Example

import numpy as np

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

Output:

[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)

Output:

['H' 'e' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd']

numpy.fromiter

numpy.fromiter method creates an ndarray object from an iterable 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, which means all data

Example

import numpy as np

# Create a list object using the range function
list = range(5)
it = iter(list)

# Create ndarray using the iterator
x = np.fromiter(it, dtype=float)
print(x)

Output:

[0. 1. 2. 3. 4.]
❮ Numpy Io Numpy Broadcast ❯