NumPy 从已有数组创建数组,本章节介绍如何从已有的数组创建数组,可以使用numpy.asarray,numpy.frombuffer,numpy.fromiter等。
numpy.asarray
numpy.asarray 类似 numpy.array,但 numpy.asarray 只有三个参数,比 numpy.array 少两个参数。
参数说明:
例1:将列表
转换为 ndarray
输出结果为:
例2:将元组
转换为 ndarray
输出结果为:
例3:将元组列表
转换为 ndarray
输出结果为:
例4:设置了 dtype 参数
输出结果为:
numpy.frombuffer
numpy.frombuffer 用于实现动态数组。
numpy.frombuffer 接受 buffer 输入参数,以流的形式读入转化成 ndarray 对象。
参数说明:
参数 | 描述 |
---|---|
buffer | 可以是任意对象,会以流的形式读入。 |
dtype | 返回数组的数据类型,可选 |
count | 读取的数据数量,默认为-1,读取所有数据。 |
offset | 读取的起始位置,默认为0。 |
注意:buffer是字符串的时候,Python3默认str是Unicode类型,所以要转成 bytestring 在原 str 前加上 b。
Python3.x 实例
输出结果为:
Python2.x 实例
输出结果为:
numpy.fromiter
numpy.fromiter 方法从可迭代对象中建立 ndarray 对象,返回一维数组。
参数 | 描述 |
---|---|
iterable | 可迭代对象 |
dtype | 返回数组的数据类型 |
count | 读取的数据数量,默认为-1,读取所有数据 |
输出结果为: