首先自定义三种类型(如下代码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的一个使用误区的更多相关文章

  1. numpy数组、向量、矩阵运算

    可以来我的Github看原文,欢迎交流. https://github.com/AsuraDong/Blog/blob/master/Articles/%E6%9C%BA%E5%99%A8%E5%AD ...

  2. Numpy数组对象的操作-索引机制、切片和迭代方法

    前几篇博文我写了数组创建和数据运算,现在我们就来看一下数组对象的操作方法.使用索引和切片的方法选择元素,还有如何数组的迭代方法. 一.索引机制 1.一维数组 In [1]: a = np.arange ...

  3. 操作 numpy 数组的常用函数

    操作 numpy 数组的常用函数 where 使用 where 函数能将索引掩码转换成索引位置: indices = where(mask) indices => (array([11, 12, ...

  4. NumPy 超详细教程(1):NumPy 数组

    系列文章地址 NumPy 最详细教程(1):NumPy 数组 NumPy 超详细教程(2):数据类型 NumPy 超详细教程(3):ndarray 的内部机理及高级迭代 文章目录 Numpy 数组:n ...

  5. Numpy 数组属性

    Numpy 数组的维数称为秩(rank),一维数组的秩为 1 , 二维数组的秩为 2 , 以此类推:在Numpy中, 每一个线性的数组称为是一个轴(axis),也就是维度(dimensios).比如说 ...

  6. numpy 数组对象

    numpy 数组对象NumPy中的ndarray是一个多维数组对象,该对象由两部分组成:实际的数据,描述这些数据的元数据# eg_v1 import numpy as np a = np.arange ...

  7. numpy 数组迭代Iterating over arrays

    在numpy 1.6中引入的迭代器对象nditer提供了许多灵活的方式来以系统的方式访问一个或多个数组的所有元素. 1 单数组迭代 该部分位于numpy-ref-1.14.5第1.15 部分Singl ...

  8. Python数据分析工具库-Numpy 数组支持库(一)

    1 Numpy数组 在Python中有类似数组功能的数据结构,比如list,但在数据量大时,list的运行速度便不尽如意,Numpy(Numerical Python)提供了真正的数组功能,以及对数据 ...

  9. numpy数组的创建

    创建数组 创建ndarray 创建数组最简单的方法就是使用array函数.它接收一切序列型的对象(包括其他数组),然后产生一个新的含有传入数据的Numpy数组. array函数创建数组 import ...

随机推荐

  1. 2018.09.24 bzoj1486: [HNOI2009]最小圈(01分数规划+spfa判负环)

    传送门 答案只保留了6位小数WA了两次233. 这就是一个简单的01分数规划. 直接二分答案,根据图中有没有负环存在进行调整. 注意二分边界. 另外dfs版spfa判负环真心快很多. 代码: #inc ...

  2. 【转】Paxos算法2-算法过程

    ——转自:{老码农的专栏} 1.编号处理 根据P2c ,proposer在提案前会先咨询acceptor查看其批准的最大的编号和value,再决定提交哪个value.之前我们一直强调更高编号的prop ...

  3. 优秀前端工程师必备: cookie的增删改查Demo!

    1 cookie可以很好地解决微信浏览器登录状态的保存,具体教程看下面链接: https://www.cnblogs.com/autoXingJY/p/10456767.html 2 参考了w3c等的 ...

  4. hdu 5025 bfs+状压

    http://acm.hdu.edu.cn/showproblem.php?pid=5025 N*N矩阵 M个钥匙 K起点,T终点,S点需多花费1点且只需要一次,1-9表示9把钥匙,只有当前有I号钥匙 ...

  5. Bellman_ford货币兑换——正权回路判断

    POJ1860 题目大意:你在某一点有一些钱,给定你两点之间钱得兑换规则,问你有没有办法使你手里的钱增多.就是想看看转一圈我的钱能不能增多,出现这一点得条件就是有兑换钱得正权回路,所以选择用bellm ...

  6. hibernate 一对多,由谁维护性能最优

    举例如下 Customer类: public class Customer { private int id; private String name; private Set orders = ne ...

  7. delphi 手机振动 IOS Android

    delphi 手机振动 IOS Android delphi  手机振动 IOS Android 振动 https://community.embarcadero.com/blogs/entry/ho ...

  8. 曲演杂坛--使用ALTER TABLE修改字段类型的吐血教训

    --===================================================================== 事件起因:开发发现有表插入数据失败,查看后发现INT类型 ...

  9. Asp.net MVC5 返回json数据忽略序列化属性

    在属性上添加 [ScriptIgnore] 特性,命名空间是System.Web.Script.Serialization

  10. MS SQL 分页存储过程

    最近换了家新公司,但是新公司没有使用分页的存储过程.那我就自个写一个往项目上套 (效率怎么样就不怎么清楚没有详细的测试过) CREATE PROCEDURE [dbo].[pro_common_pag ...