Share @ LinkedIn Facebook  numpy, basics
Learning Numpy - Simple Tutorial For Beginners - NumPy - Array From Existing Data Part 6

Learning Numpy - Simple Tutorial For Beginners - NumPy - Array From Existing Data Part 6

numpy.asarray

This function is similar to numpy.array except for the fact that it has fewer parameters. This routine is useful for converting Python sequence into ndarray.

numpy.asarray(a, dtype = None, order = None)
Parameter Description
a Input data in any form such as list, list of tuples, tuples, tuple of tuples or tuple of lists
Dtype By default, the data type of input data is applied to the resultant ndarray
Order C (row major) or F (column major). C is default

Example 1

In [1]:
# convert list to ndarray 
import numpy as np

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

Example 2

In [1]:
# dtype is set 
import numpy as np

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

Example 3

In [3]:
# ndarray from tuple 
import numpy as np

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

Example 4

In [4]:
# ndarray from list of tuples 
import numpy as np

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

numpy.frombuffer

This function interprets a buffer as one-dimensional array. Any object that exposes the buffer interface is used as parameter to return an ndarray.

numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)
Parameter Description
buffer Any object that exposes buffer interface
dtype Data type of returned ndarray. Defaults to float
count The number of items to read, default -1 means all data
offset The starting position to read from. Default is 0

numpy.fromiter

This function builds an ndarray object from any iterable object. A new one-dimensional array is returned by this function.

numpy.fromiter(iterable, dtype, count = -1)
Parameter Description
iterable Any iterable object
dtype Data type of resultant array
count The number of items to be read from iterator. Default is -1 which means all data to be read

Example 1

In [11]:
# create list object using range function 
import numpy as np
list = range(5)
print (list)
range(0, 5)

Example 2

In [12]:
# obtain iterator object from list 
import numpy as np
list = range(5)
it = iter(list)

# use iterator to create ndarray 
x = np.fromiter(it, dtype = float)
print (x)
[0. 1. 2. 3. 4.]


Dolly Solanki  Dolly Solanki