欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

B04_NumPy从已有的数组创建数组(numpy.asarray,numpy.frombuffer,numpy.fromiter)

发布时间:2024/9/27 编程问答 42 豆豆
生活随笔 收集整理的这篇文章主要介绍了 B04_NumPy从已有的数组创建数组(numpy.asarray,numpy.frombuffer,numpy.fromiter) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

NumPy从已有的数组创建数组

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

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

参数说明:

参数描述
a任意形式的输入参数,可以是,列表, 列表的元组, 元组, 元组的元组, 元组的列表,多维数组
dtype数据类型,可选
order可选,有"C"和"F"两个选项,分别代表,行优先和列优先,在计算机内存中的存储元素的顺序。

实例
将列表转换为 ndarray:

# -*- coding: UTF-8 -*-import numpy as npx = [1,2,3] a = np.asarray(x) print(a)

输出结果为:

[1 2 3]

将元组转换为 ndarray:

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

输出结果为:

[1 2 3]

将元组列表转换为 ndarray:

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

输出结果为:

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

设置了dtype参数:

import numpy as npx = [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 是字符串的时候,Python3 默认 str 是 Unicode 类型,所以要转成 bytestring 在原 str 前加上 b。

参数说明:

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

Python 3.x实例

import numpy as nps = 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.]

总结

以上是生活随笔为你收集整理的B04_NumPy从已有的数组创建数组(numpy.asarray,numpy.frombuffer,numpy.fromiter)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。