除了新建数组外,还可以通过已有的数组来创建数组。
(1)numpy.asarray:类似于numpy.array,但是numpy.asarray参数只有三个,比numpy.array少两个。
numpy.asarray(a, dtype = None, order = None)
其中,a是任意形式的输入参数,可以是列表、列表的元组、元组、元组的元组、元组的列表和多维数组;dtype表示数据类型,可选;order可选,有"C"和"F"两个选项,分别代表行优先和列优先(在计算机内存中存储元素的顺序)。比如将列表转换为ndarray:
x = [1,2,3] a = np.asarray(x) print (a)
输出结果为:[1 2 3]。再将元组转换为ndarray:
x = (1,2,3) a = np.asarray(x) print (a)
输出结果为:[1 2 3]。再看设置了dtype的参数:
x = [1,2,3] a = np.asarray(x, dtype = float) print (a)
输出结果为:[1. 2. 3.]。
(2)numpy.frombuffer:用于实现动态数组。numpy.frombuffer接受buffer输入参数,以流的形式读入转化成ndarray对象:
numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)
其中,参数buffer可以是任意对象,会以流的形式读入;dtype表示返回数组的数据类型,可选;count表示读取的数据数量,默认为‒1,读取所有数据;offset表示读取的起始位置,默认为0。
buffer是字符串的时候,Python 3默认str是Unicode类型,所以要转成bytestring可在原str前加上b。比如:
s = b'Hello World' a = np.frombuffer(s, dtype = 'S1') print (a)
输出结果为:[b'H' b'e' b'l' b'l' b'o' b' ' b'W' b'o' b'r' b'l' b'd']。
(3)numpy.fromiter:从可迭代对象中建立ndarray对象,返回一维数组。
numpy.fromiter(iterable, dtype, count=-1)
其中,参数iterable表示可迭代对象;dtype表示返回数组的数据类型;count表示读取的数据数量,默认为-1,读取所有数据。比如:
# 使用range函数创建列表对象 list=range(5) it=iter(list) # 使用迭代器创建 ndarray x=np.fromiter(it, dtype=float) print(x)
输出结果为:[0. 1. 2. 3. 4.]。