NumPy 从已有数组创建数组 您所在的位置:网站首页 numpy怎么创建二维数组 NumPy 从已有数组创建数组

NumPy 从已有数组创建数组

#NumPy 从已有数组创建数组| 来源: 网络整理| 查看: 265

NumPy 从已有数组创建数组,本章节介绍如何从已有的数组创建数组,可以使用numpy.asarray,numpy.frombuffer,numpy.fromiter等。

numpy.asarray

numpy.asarray 类似 numpy.array,但 numpy.asarray 只有三个参数,比 numpy.array 少两个参数。

numpy.asarray(a, dtype = None, order = None)

参数说明: NumPy 从已有数组创建数组

例1:将列表转换为 ndarray

import numpy as np x = [1,2,3] a = np.asarray(x) print (a)

输出结果为:

[1 2 3]

例2:将元组转换为 ndarray

import numpy as np x = (1,2,3) a = np.asarray(x) print (a)

输出结果为:

[1 2 3]

例3:将元组列表转换为 ndarray

import numpy as np x = [(1,2,3),(4,5)] a = np.asarray(x) print (a)

输出结果为:

[(1, 2, 3) (4, 5)]

例4:设置了 dtype 参数

import numpy as np x = [1,2,3] a = np.asarray(x, dtype = float) print (a)

输出结果为:

[ 1. 2. 3.] numpy.frombuffer

numpy.frombuffer 用于实现动态数组。 numpy.frombuffer 接受 buffer 输入参数,以流的形式读入转化成 ndarray 对象。

numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)

参数说明:

参数 描述 buffer 可以是任意对象,会以流的形式读入。 dtype 返回数组的数据类型,可选 count 读取的数据数量,默认为-1,读取所有数据。 offset 读取的起始位置,默认为0。

注意:buffer是字符串的时候,Python3默认str是Unicode类型,所以要转成 bytestring 在原 str 前加上 b。

Python3.x 实例

import numpy as np 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']

Python2.x 实例

import numpy as np s = 'Hello World' a = np.frombuffer(s, dtype = 'S1') print (a)

输出结果为:

['H' 'e' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd'] numpy.fromiter

numpy.fromiter 方法从可迭代对象中建立 ndarray 对象,返回一维数组。

numpy.fromiter(iterable, dtype, count=-1) 参数 描述 iterable 可迭代对象 dtype 返回数组的数据类型 count 读取的数据数量,默认为-1,读取所有数据 import numpy as np # 使用 range 函数创建列表对象 list=range(5) it=iter(list) # 使用迭代器创建 ndarray x=np.fromiter(it, dtype=float) print(x)

输出结果为:

[0. 1. 2. 3. 4.]


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有