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:
| Parameters | Description |
|---|---|
| a | Any form of input parameter, which can be a list, a tuple of lists, a tuple, a tuple of tuples, a list of tuples, or a multi-dimensional array |
| dtype | Data type, optional |
| order | Optional. There are two options, 'C' and 'F', representing row-major and column-major respectively, the order in which elements are stored in computer memory. |
Example
Convert a list to an ndarray:
Example
import
numpy
as
np
x
=
[
1
,
2
,
3
]
a
=
np
.
asarray
(
x
)
(
a
)
The output is:
[1 2 3]
Convert a tuple to an ndarray:
Example
import
numpy
as
np
x
=
(
1
,
2
,
3
)
a
=
np
.
asarray
(
x
)
(
a
)
The output is:
[1 2 3]
Convert a list of tuples to an ndarray:
Example
import
numpy
as
np
x
=
[
(
1
,
2
,
3
)
,
(
4
,
5
)
]
a
=
np
.
asarray
(
x
)
(
a
)
The output is:
[(1, 2, 3) (4, 5)]
Setting the dtype parameter:
Example
import
numpy
as
np
x
=
[
1
,
2
,
3
]
a
=
np
.
asarray
(
x
,
dtype
=
float
)
(
a
)
The output is:
[ 1. 2. 3.]
numpy.frombuffer
numpy.frombuffer is used to implement dynamic arrays.
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 buffer is a string, Python3's default str is the Unicode type, so to convert it to a bytestring, add b before the original str.
Parameter Description:
| Parameters | Description |
|---|---|
| buffer | Can be any object, which will be read in as a stream. |
| dtype | The data type of the returned array, optional |
| count | The number of data items to read, defaults to -1, which reads all data. |
| offset | The starting position to read from, defaults to 0. |
Python3.x example
import
numpy
as
np
s
=
b
'
Hello World
'
a
=
np
.
frombuffer
(
s
,
dtype
=
'
S1
'
)
(
a
)
The output is:
[b'H' b'e' b'l' b'l' b'o' b' ' b'W' b'o' b'r' b'l' b'd']
Python 2.x example
import
numpy
as
np
s
=
'
Hello World
'
a
=
np
.
frombuffer
(
s
,
dtype
=
'
S1
'
)
(
a
)
The output is:
['H' 'e' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd']
numpy.fromiter
The numpy.fromiter method creates an ndarray object from an iterable and returns a one-dimensional array.
numpy.fromiter(iterable, dtype, count=-1)
| Parameters | Description |
|---|---|
| iterable | Iterable objects |
| dtype | The data type of the returned array |
| count | The number of items to read, defaults to -1, meaning read all data |
Example
import
numpy
as
np
Use the range function to create a list object
list
=
range
(
5
)
it
=
iter
(
list
)
Create an ndarray using an iterator
x
=
np
.
fromiter
(
it
,
dtype
=
float
)
(
x
)
The output is:
[0. 1. 2. 3. 4.]