6、Numpy从已有的数组创建数组

1、番外说明

大家好,我是小P,本系列是本人对Python模块Numpy的一些学习记录,总结于此一方面方便其它初学者学习,另一方面害怕自己遗忘,希望大家喜欢。此外,对“目标检测/模型压缩/语义分割”感兴趣的小伙伴,欢迎加入QQ群 813221712 讨论交流,进群请看群公告!(可以点击如下连接直接加入!)
点击链接加入群聊【Object Detection】:https://jq.qq.com/?_wv=1027&k=5kXCXF8

2、正题

参考链接:
http://www.runoob.com/numpy/numpy-array-from-existing-data.html
2.1 numpy.asarray函数

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

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

参数说明:
在这里插入图片描述
实例:将列表转换为 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.]
2.2 numpy.frombuffer

numpy.frombuffer 用于实现动态数组。

numpy.frombuffer 接受 buffer 输入参数,以流的形式读入转化成 ndarray 对象。

numpy.frombuffer(buffer, dtype = float, 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']
2.3 numpy.fromiter

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

numpy.fromiter(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.]
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值