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 |
# convert list to ndarray
import numpy as np
x = [1,2,3]
a = np.asarray(x)
print (a)
# dtype is set
import numpy as np
x = [1,2,3]
a = np.asarray(x, dtype = float)
print (a)
# ndarray from tuple
import numpy as np
x = (1,2,3)
a = np.asarray(x)
print (a)
# ndarray from list of tuples
import numpy as np
x = [(1,2,3),(4,5)]
a = np.asarray(x)
print (a)
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 |
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 |
# create list object using range function
import numpy as np
list = range(5)
print (list)
# 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)