NumPy 提供了一种通过使用现有数据来创建数组的方式。numpy.asarray
这个例程用于通过使用列表或元组等形式的现有数据来创建数组。在需要将 Python 序列转换为 NumPy 数组对象的场景中非常有用。numpy.asarray(sequence, dtype=None, order=None)
- sequence:要转换为数组的 Python 序列。
示例:使用列表创建 Numpy 数组
import numpy as npl = [1, 2, 3, 4, 5, 6, 7]a = np.asarray(l)print(type(a))print(a)
<class 'numpy.ndarray'>[1 2 3 4 5 6 7]
专属福利
示例:使用元组创建 Numpy 数组
import numpy as npl = (1, 2, 3, 4, 5, 6, 7)a = np.asarray(l)print(type(a))print(a)
<class 'numpy.ndarray'>[1 2 3 4 5 6 7]
示例:使用多个列表创建 Numpy 数组
import numpy as npl = [[1, 2, 3, 4, 5, 6, 7], [8, 9]]a = np.asarray(l)print(type(a))print(a)
<class 'numpy.ndarray'>[list([1, 2, 3, 4, 5, 6, 7]) list([8, 9])]
numpy.frombuffer
这个函数用于通过指定的缓冲区创建数组。使用该缓冲区的语法如下。numpy.frombuffer(buffer, dtype=float, count=-1, offset=0)
- dtype:返回的数据类型数组的数据类型。默认值为 0。
- count:返回的 ndarray 的长度。默认值为 -1。
示例
import numpy as npl = b'hello world'print(type(l))a = np.frombuffer(l, dtype="S1")print(a)print(type(a))
<class 'bytes'>[b'h' b'e' b'l' b'l' b'o' b' ' b'w' b'o' b'r' b'l' b'd']<class 'numpy.ndarray'>
numpy.fromiter
这个例程用于通过使用可迭代对象创建一个 ndarray。它返回一个一维的 ndarray 对象。numpy.fromiter(iterable, dtype, count=-1)
示例
import numpy as nplst = [0, 2, 4, 6]it = iter(lst)x = np.fromiter(it, dtype=float)print(x)print(type(x))
[0. 2. 4. 6.]<class 'numpy.ndarray'>
