Numpy Array From Existing Data
# NumPy Creating Arrays from Existing Data
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 fewer 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, multidimensional array. |
| dtype | Data type, optional. |
| order | Optional. Can be "C" or "F", representing row-major (C-style) or column-major (Fortran-style) order in memory. |
### Example
Convert a list to an ndarray:
## Example
import numpy as np x = [1,2,3]a = np.asarray(x)print(a)
Output:
Convert a tuple to an ndarray:
## Example
import numpy as np x = (1,2,3)a = np.asarray(x)print(a)
Output:
Convert a list of tuples to an ndarray:
## Example
import numpy as np x = [(1,2,3),(4,5)]a = np.asarray(x)print(a)
Output:
[(1, 2, 3) (4, 5)]
Setting the dtype parameter:
## Example
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 to create a dynamic array.
numpy.frombuffer takes 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 to Unicode strings, so you need to convert it to a bytestring by adding a `b` before the original string.
Parameter Description:
| Parameter | Description |
| --- | --- |
| buffer | Any object that can be read as a stream. |
| dtype | Data type of the returned array, optional. |
| count | Number of data items to read. Default is -1, which 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)
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
The numpy.fromiter method creates an ndarray object from an iterable object, returning a one-dimensional array.
numpy.fromiter(iterable, dtype, count=-1)
| Parameter | Description |
| --- | --- |
| iterable | An iterable object. |
| dtype | Data type of the returned array. |
| count | Number of data items to read. Default is -1, which reads all data. |
## Example
import numpy as np# Create a list object using the range function list=range(5)it=iter(list)# Create an ndarray using the iterator x=np.fromiter(it, dtype=float)print(x)
Output:
[0. 1. 2. 3. 4.]
YouTip