NumPy提供了使用现有数据创建数组的方法。
要使用列表或元组创建ndarray数组,可使用asarray
函数。这个函数通常用于将python序列转换为numpy数组对象的场景中。
语法如下所示:
numpy.asarray(sequence, dtype = None, order = None)
参数:
示例
使用列表创建numpy数组
import numpy as np
l=[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]
示例
使用元组创建一个ndarray数组
import numpy as np
l=(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]
示例
使用多个列表创建ndarray数组
import numpy as np
l=[[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])]
要使用指定的缓冲区创建数组,可以用frombuffer
函数。
语法如下所示:
numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)
参数:
示例
import numpy as np
l = 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'>
要使用可迭代对象创建ndarray数组,可以使用fromiter
函数。fromiter
函数返回一个一维的ndarray数组。
语法如下所示:
numpy.fromiter(iterable, dtype, count = - 1)
参数:
示例
import numpy as np
list = [0,2,4,6]
it = iter(list)
x = np.fromiter(it, dtype = float, count = 2)
print(x)
print(type(x))
输出
[0. 2.]
<class 'numpy.ndarray'>
原文:https://www.cnblogs.com/jinbuqi/p/11319630.html