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 ...
随机推荐
- py-opp 类(class)
类的创建 class 类名: pass class Bar: def foo(self,arg): # self ,是传的实例对象, print('self:',self,arg) #因为类属性和方法 ...
- struts2从浅至深(六)contextMap(存取数据)
A:存数据 1.利用ActionContext存数据 这种方式最简便 这是一个购物车案例 把查询来的数据放入到Session中存储起来 2.利用valuestack值栈存数据 把查询出来的数据放入到值 ...
- hdu 5882 Balanced Game 2016-09-21 21:22 80人阅读 评论(0) 收藏
Balanced Game Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) To ...
- MFC中和定时器使用
在MFC中和定时器相关的有三个函数: 1.设置定时器(定义一个定时器的属性): SetTimer( UINT nIDEvent, UINT nElapse, void (CALLBAC ...
- OneDrive不能上了?DNS被污染,解决方法很简单
http://www.expreview.com/34434.html 除了LINE以外,最近微软的OneDrive云存储服务也出现访问故障,不过@月光博客 表示它只是受到DNS污染,被解析为无法访问 ...
- Android-Android7.0-java.lang.SecurityException: MODE_WORLD_READABLE no longer supported
某个AndroidProject项目在Android5.0系统运行是OK的,在Android7.0以上版本运行,报以下错误❌ 2019-01-02 15:33:39.996 17067-17067/? ...
- Linux 安装PAE内核
客户软件是部署在32位的CentOS5服务器当中,CentOS5目前只能识别4G内存,需要安装PAE内核,让系统支持PAE物理地址扩展. 1.安装PAE内核 yum -y install kern ...
- linux系统编程之信号(四):alarm和可重入函数
一,alarm() 在将可重入函数之前我们先来了解下alarm()函数使用: #include <unistd.h> unsigned int alarm(unsigned int sec ...
- ==和Equals与值类型和引用类型
==和Equals 对于值类型来说判断的是值,对于引用类型来说判断的是堆地址 注意:string 是引用类型(也可看做只读char[]数组)(字符串的不可变性·拘留池)特殊的值类型(使用==.Equa ...
- Linear and Quadratic Programming Solver ( Arithmetic and Algebra) CGAL 4.13 -User Manual
1 Which Programs can be Solved? This package lets you solve convex quadratic programs of the general ...