当前位置: 代码网 > it编程>编程语言>C/C++ > NumPy实现从已有的数组创建数组

NumPy实现从已有的数组创建数组

2024年10月08日 C/C++ 我要评论
一. 前言本章节我们将学习如何从已有的数组创建数组。二. numpy.asarraynumpy.asarray 类似 numpy.array,但 numpy.asarray 参数只有三个,比 nump

一. 前言

本章节我们将学习如何从已有的数组创建数组。

二. numpy.asarray

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

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

参数说明:

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

实例

将列表转换为 ndarray:

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

输出结果为:

[1  2  3]

将元组转换为 ndarray:

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

输出结果为:

[1  2  3]

将元组列表转换为 ndarray:

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

输出结果为:

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

设置了 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 是字符串的时候,python3 默认 str 是 unicode 类型,所以要转成 bytestring 在原 str 前加上 b。

参数说明:

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

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.]

到此这篇关于numpy实现从已有的数组创建数组的文章就介绍到这了,更多相关numpy 从已有的数组创建数组内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com