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 ...
随机推荐
- Django入门指南-第8章:第一个测试用例(完结)
python manage.py test python manage.py test --verbosity=2 # boards/tests.py from django.core.urlreso ...
- 设定Word段落的背景色
段落背景不同于文字区别.很多新接触word的朋友都找不到怎么弄. 先把光标停留在需要设置的段落文字上,或者选择需要设置的段落文字. 点击段落里的边框和底纹,如图 在弹出框中选择底纹. 选择需要填充的颜 ...
- 继承方法-->最终模式
function inherit(Target,Origin){ function F(){}; F.prototype = Origin.prototype; // Targrt.prototype ...
- nexus 组件下载和上传
一. 重写 super pom 修改 maven 的 settings.xml Configuring Maven to Use a Single Repository Group <setti ...
- HBase Thrift2 CPU过高问题分析
目录 目录 1 1. 现象描述 1 2. 问题定位 2 3. 解决方案 5 4. 相关代码 5 1. 现象描述 外界连接9090端口均超时,但telnet端口总是成功.使用top命令观察,发现单个线程 ...
- mysql-5.7.10普通安装
这里安装的是最新的MySQL 5.7.10,下载网址为:http://dev.mysql.com/downloads/mysql/,本文选择是的"Linux - Generic"下 ...
- MySQL性能调优与架构设计——第 15 章 可扩展性设计之Cache与Search的利用
第 15 章 可扩展性设计之Cache与Search的利用 前言: 前面章节部分所分析的可扩展架构方案,基本上都是围绕在数据库自身来进行的,这样是否会使我们在寻求扩展性之路的思维受到“禁锢”,无法更为 ...
- session token防表单重提
1.表单页面初始化前,先在session存入一个token值,随后把token存放在表单页面隐藏表单域内,开始初始化: 在表单页初始化前,调用ajax请求,在后台生成token,并返回至表单页 fun ...
- maven下@override标签失效
经常遇见此问题,现记录如下,以备下次查阅. 在pom文件添加配置: <plugin> <groupId>org.apache.maven.plugins</groupId ...
- KNN PCA LDA
http://blog.csdn.net/scyscyao/article/details/5987581 这学期选了门模式识别的课.发现最常见的一种情况就是,书上写的老师ppt上写的都看不懂,然后绕 ...