Numpy 数组和dtype的一个使用误区
首先自定义三种类型(如下代码1-3行),第一行使用scalar type,第2,3行使用Structured type。
提出问题:第5,7行同为创建数组,为什么第5行能work,而第7行会raise一个exception:expected an object with a buffer interface呢?
问题解答:原因在于创建numpy数组时,如果指定dtype是Structured type时,List(本例中[1,2])中的元素必须是元组类型的。但是第7行是一般的int型。所以出错。如果指定dtype是scalar type则没有此限制。
后续问题:根据以上分析结果,自然就有了第12行代码。但是错误依然:expected an object with a buffer interface。 但是如果自定义类型有两个或以上的字段(代码3,10),则毫无问题。为什么呢?
问题解答:问题出在元组这边,但定义的元组中只含有一个元素时,该元组就会退化为一般的数据类型而不会被作为元组对待。
解决办法就是如代码14行这样定义List.
另外一种解决方案就是:使用数组的view方法:a=np.array([1,2]).view(dt2)。 效果和代码14行是一样的。
dt1=np.dtype(np.int32)
dt2=np.dtype([('f1', np.int32)])
dt3=np.dtype([('f1', np.int32), ('f2', np.int32)]) a=np.array([1,2],dtype=dt1)
print a
a=np.array([1,2],dtype=dt2)
#error: expected an object with a buffer interface a=np.array([(1,2),(3,4)],dtype=dt3)
print a
a=np.array([(1),(2)],dtype=dt2)
#error: expected an object with a buffer interface
a=np.array([(1,),(2,)],dtype=dt2)
其他dtype的使用范例:
import numpy as np
import sys def dTypeTest():
#Using dictionaries. Two fields named ‘gender’ and ‘age’:
student=np.dtype({'names':['name', 'age', 'weight'],'formats':['S32', 'i','f']}, align=True)
a=np.array([('zhang',65,123.5),('wang',23,122.5)],dtype=student)
print a
#Using array-scalar type:
a=np.array([1,2],dtype=np.dtype(np.int16))
print a #Structured type, one field name 'f1', containing int16:
#a=np.array([1,2],dtype=np.dtype([('f1', np.int16)]))
a=np.array([1,2]).view(np.dtype([('f1', np.int16)]))
print a
a=np.array([1,2]).view(np.dtype([('f1', np.int32)]))
print a
a=np.array([(1,),(2,)],dtype=np.dtype([('f1', np.int16)]))
print a
#below two lines of code is not working as [1,2] is not a list of tuple
#a=np.array([1,2],dtype=np.dtype([('f1', np.int16)]))
#a=np.array([(1),(2,)],dtype=np.dtype([('f1', np.int16)])) #Structured type, one field named ‘f1’, in itself containing a structured type with one field:
dt=np.dtype([('f1', [('f1', np.int32)])])
a=np.array([1,2]).view(dt)
print a
a=np.array([((1,),),((2,),)],dtype=dt)
print a
#below two lines of code is not working as (1,) is not same as the structure of dtype declared
#a=np.array([(1,),(2,)],dtype=dt) #Structured type, two fields: the first field contains an unsigned int, the second an int32
dt=np.dtype([('f1', np.uint), ('f2', np.int32)])
a=np.array([(1,2),(3,4)],dtype=dt)
print a #Using array-protocol type strings:
dt=np.dtype([('a','f8'),('b','S10')])
a=np.array([(3.14,'pi'),(2.17,'e')],dtype=dt)
print a #Using comma-separated field formats. The shape is (2,3):
dt=np.dtype("i4, (2,3)f8")
a=np.array([(1,[[1,2,3],[4,5,6]]),(2,[[4,5,6],[1,2,3]])],dtype=dt)
print a #Using tuples. int is a fixed type, 3 the field’s shape. void is a flexible type, here of size 10
dt=np.dtype([('hello',(np.int,3)),('world',np.void,10)])
a=np.array([([1,2,3],'this is a')],dtype=dt)
print a def main():
dTypeTest() if __name__ == "__main__":
main()
Numpy 数组和dtype的一个使用误区的更多相关文章
- numpy数组、向量、矩阵运算
可以来我的Github看原文,欢迎交流. https://github.com/AsuraDong/Blog/blob/master/Articles/%E6%9C%BA%E5%99%A8%E5%AD ...
- Numpy数组对象的操作-索引机制、切片和迭代方法
前几篇博文我写了数组创建和数据运算,现在我们就来看一下数组对象的操作方法.使用索引和切片的方法选择元素,还有如何数组的迭代方法. 一.索引机制 1.一维数组 In [1]: a = np.arange ...
- 操作 numpy 数组的常用函数
操作 numpy 数组的常用函数 where 使用 where 函数能将索引掩码转换成索引位置: indices = where(mask) indices => (array([11, 12, ...
- NumPy 超详细教程(1):NumPy 数组
系列文章地址 NumPy 最详细教程(1):NumPy 数组 NumPy 超详细教程(2):数据类型 NumPy 超详细教程(3):ndarray 的内部机理及高级迭代 文章目录 Numpy 数组:n ...
- Numpy 数组属性
Numpy 数组的维数称为秩(rank),一维数组的秩为 1 , 二维数组的秩为 2 , 以此类推:在Numpy中, 每一个线性的数组称为是一个轴(axis),也就是维度(dimensios).比如说 ...
- numpy 数组对象
numpy 数组对象NumPy中的ndarray是一个多维数组对象,该对象由两部分组成:实际的数据,描述这些数据的元数据# eg_v1 import numpy as np a = np.arange ...
- numpy 数组迭代Iterating over arrays
在numpy 1.6中引入的迭代器对象nditer提供了许多灵活的方式来以系统的方式访问一个或多个数组的所有元素. 1 单数组迭代 该部分位于numpy-ref-1.14.5第1.15 部分Singl ...
- Python数据分析工具库-Numpy 数组支持库(一)
1 Numpy数组 在Python中有类似数组功能的数据结构,比如list,但在数据量大时,list的运行速度便不尽如意,Numpy(Numerical Python)提供了真正的数组功能,以及对数据 ...
- numpy数组的创建
创建数组 创建ndarray 创建数组最简单的方法就是使用array函数.它接收一切序列型的对象(包括其他数组),然后产生一个新的含有传入数据的Numpy数组. array函数创建数组 import ...
随机推荐
- 2018.07.07 BZOJ2212: Poi2011Tree Rotations(线段树合并)
2212: [Poi2011]Tree Rotations Time Limit: 20 Sec Memory Limit: 259 MB Description Byteasar the garde ...
- c语言中几个常见的库函数strlen、strcmp、strcat、strcpy、strncpy、memset、memcpy、memmove、mmap
1.strlen() 1)计算给定字符串的长度,不包括’\0’在内 unsigned int strlen(const char *s) { assert(NULL != s);//如果条件不满足,则 ...
- Creating a Simple Web Service and Client with JAX-WS
Creating a Simple Web Service and Client with JAX-WS 发布服务 package cn.zno.service.impl; import javax. ...
- HDU4081 Qin Shi Huang's National Road System 2017-05-10 23:16 41人阅读 评论(0) 收藏
Qin Shi Huang's National Road System ...
- Eclipse ADT 代码注释模版
具体怎么用: 将下面的内容拷贝出来保存为XML文件,进入,Eclipse :Window --> Java --> Code Style --> Code Templates-> ...
- linux系统编程之管道(三):命令管道(FIFO)
一,匿名管道PIPE局限性 管道的主要局限性正体现在它的特点上: 只支持单向数据流: 只能用于具有亲缘关系的进程之间: 没有名字: 管道的缓冲区是有限的(管道制存在于内存中,在管道创建时,为缓冲区分配 ...
- Replication--复制事务和复制命令
--=============================================== 对复制一直属于一知半解浑浑噩噩的状态,仅知道一些皮毛,对很多细节没有深入学习过, 如果不对之处,请各 ...
- .Net Core2.0中使用ADO.NET
学习了解.NET CORE有段时间,没有用其做项目的主要原因就是这么多年积累的类库兼容问题.今天就先解决SqlHelper的兼容性: 建立类库,目标框架选择.NET Core2.0,复制粘贴代码. 问 ...
- VS未能正确加载 ”Microsoft.VisualStudio.Editor.Implementation.EditorPackate“包错误解决方法
很久没用VS了,打开后出现未能正确加载 ”Microsoft.VisualStudio.Editor.Implementation.EditorPackate“包的错误,经过一番上网查阅错误得以解决. ...
- C# GDI绘制波形图
直接上效果图如下 public partial class WaveChartUserCtrl : UserControl { Color axisColor = Color.FromArgb(69, ...