numpy 学习汇总21 - 循环迭代a.data,np.flat,np.nditer(详解 基础学习 tcy)
发布日期:2021-06-29 14:47:35 浏览次数:3 分类:技术文章

本文共 6229 字,大约阅读时间需要 20 分钟。

循环迭代 2018/11/23   2018/11/28    ==================================================================1.普通循环    a = np.arange(12).reshape(3, 4)print(f'a={a}')              # a=[[ 0  1  2  3][ 4  5  6  7][ 8  9 10 11]]    for row in a:               # 迭代数组1    print(row,end=' ; ')  # [0 1 2 3] ; [4 5 6 7] ; [ 8  9 10 11] ;    for row in a:               # 迭代数组2    for cell in row:print(cell,end=',')    2.数组迭代np.flat 属性#是数组中所有元素的迭代器 :    x=np.arange(12)for i in x.data:            #x的视图仅支持1D    print(i,end=',')    x = np.arange(12).reshape(3, 4)for item in x.flat:        # 用np.flat属性迭代数组中每一个元素    print( item,end=',') #0,1,2,3,4,5,6,7,8,9,10,11,        ==================================================================3.np.nditer-广播迭代    # 例1:如果两个数组是可广播的,nditer 组合对象能够同时迭代它们。a = np.arange(12).reshape(3,4)b = np.array([1,  2,  3,  4], dtype =  int)    for x,y in np.nditer([a,b]):                    #数组 b 被广播到 a 的大小    print ("%d,%d"  %  (x,y), end=" ; " )#0,1;1,2;2,3;3,4;4,1;5,2;6,3;7,4;8,1;9,2;10,3;11,4 ;    # 例2:迭代器分配的输出数组:def square(a):     it = np.nditer([a, None])     for x, y in it:y[...] = x*x     return it.operands[1]    print(square([1,2,3]) )#array([1, 4, 9])                                  # 默认nditer使用标志'allocate'和'writeonly'作为None传入的操作数                                  # 例3:迭代器分配的输出数组,禁止广播def square(a, out=None):     it = np.nditer([a, out],             flags = ['external_loop', 'buffered'],             op_flags = [['readonly'],['writeonly', 'allocate', 'no_broadcast']])# 'no_broadcast'阻止播放输出     for x, y in it:         y[] = x*x     return it.operands[1]    square([1,2,3])           # array([1, 4, 9])b = np.zeros((3,))square([1,2,3], out=b)# array([ 1.,  4.,  9.])b                                # array([ 1.,  4.,  9.])square(np.arange(6).reshape(2,3), out=b)#错误,禁止广播    # np.nditer详细说明见备注==================================================================4.可迭代对象中建立数组    np.fromiter(iterabe, dtype, count=-1) #从可迭代对象中建立,返回1D数组。    iterator=iter(range(5))iterator = (x*x for x in range(5))np.fromiter(iterator,dtype= float)   #array([  0.,   1.,   4.,   9.,  16.])    ==================================================================5.备注:    np.nditer(op,[order='K',flags,op_flags]) #迭代器,访问数组的每个元素# 参数:op:迭代数组#           order顺序 :# {'C','F','A','K'},order ='K'默认内存排序#           op_flags:   #修改数组中元素值['readonly'], ['writeonly'], ['readwrite'],['readonly','copy'];默认只读#           flags:#                       flags=['external_loop'] 外部循环 (效率高)#给出值一维数组#                       flags=['external_loop','buffered']#                       flags=['buffered'],#                       flags=['c_index']      # 跟踪索引;可以跟踪 C 顺序的索引#                       flags=['f_index']       # 跟踪索引;可以跟踪 Fortran 顺序的索引#                       flags=['multi_index'] # 或多重索引;每次迭代可以跟踪一种索引类型#                                                      # 跟踪索引或多索引与使用外部循环不兼容#           op_dtypes=['complex128']# 多参数实例:flags=['buffered'], op_dtypes=['float32'], casting='same_kind'--------------------------------------------------------------------------------------------------------    # 实例1:import numpy as np    a = np.arange(6).reshape(2,3)# [[0 1 2][3 4 5]]c=a.copy(order='C')                 # [[0 1 2][3 4 5]]f=a.copy(order='F')                  # [[0 1 2][3 4 5]]    #迭代函数定义def iter0(a,order='K',op_flags=['readonly'],flags=None):    if flags!=None:        t=np.nditer(a,order=order,op_flags=op_flags,flags=flags)    else:        t = np.nditer(a, order=order, op_flags=op_flags)    b='write' in op_flags[0]    for x in t:        if b: x[...] = 2 * x        print (x, end=", " )    print ('\n')    # 1.控制遍历顺序iter0(a)      # 0, 1, 2, 3, 4, 5,iter0(a.T)   # 0, 1, 2, 3, 4, 5, # a 和 a.T 的遍历顺序是一样    # 2.迭代次序iter0(a,'A') # 0, 1, 2, 3, 4, 5,iter0(a,'C') # 0, 1, 2, 3, 4, 5, # C order,即是行序优先;iter0(a,'F') # 0, 3, 1, 4, 2, 5, # Fortran order,即是列序优先;    # 3.修改数组中元素的值iter0(a,op_flags=['readwrite'])#0, 2, 4, 6, 8, 10,    # 4.外部循环 (效率高) : 迭代器遍历并组合为一维数组。# 默认保持本机内存顺序,迭代器提供单个一维块,强制Fortran顺序提供三个两元素块。iter0(a,flags=['external_loop'], order =  'C')# [ 0  2  4  6  8 10],iter0(a,flags=['external_loop'], order =  'F')# [0 6], [2 8], [ 4 10],---------------------------------------------------------------------------------------------------------# 实例2:# 5.跟踪索引或多重索引(索引到迭代器来访问当前值)a = np.arange(6).reshape(2,3)it = np.nditer(a, flags=['f_index'])    while not it.finished:     print( "%d <%d>" % (it[0], it.index),)     it.iternext() # 0 <0> 1 <2> 2 <4> 3 <1> 4 <3> 5 <5>    it = np.nditer(a, flags=['multi_index'])while not it.finished:     print( "%d <%s>" % (it[0], it.multi_index),)     it.iternext() #0 <(0, 0)> 1 <(0, 1)> 2 <(0, 2)> 3 <(1, 0)> 4 <(1, 1)> 5 <(1, 2)>    it = np.nditer(a, flags=['multi_index'], op_flags=['writeonly'])while not it.finished:     it[0] = it.multi_index[1] - it.multi_index[0]     it.iternext()    a# array([[ 0,  1,  2],[-1,  0,  1]])--------------------------------------------------------------------------------------------------------# 实例3:# 6.缓冲数组元素(使迭代器提供给内部循环的块变大)a = np.arange(6).reshape(2,3)for x in np.nditer(a, flags=['external_loop'], order='F'):print(x)                  #[0 3] [1 4] [2 5]for x in np.nditer(a, flags=['external_loop','buffered'], order='F'):print(x)#[0 3 1 4 2 5]    # 7.特定数据类型迭代# 有时需要将数组视为与存储数据类型不同的数据类型。临时拷贝 消耗大量内存# 缓冲模式没有启用复制或缓冲模式,如果数据类型不准确,迭代器将引发异常。    a = np.arange(6).reshape(2,3) - 3for x in np.nditer(a, op_dtypes=['complex128']):     print( np.sqrt(x),)#错误 缓冲区禁止    # 8.在复制模式下,'copy'被指定为每个操作数标志。这是为了以操作数方式提供控制。缓冲模式被指定为迭代器标志。a = np.arange(6).reshape(2,3) - 3for x in np.nditer(a, op_flags=['readonly','copy'],op_dtypes=['complex128']):    print(np.sqrt(x),) # flags=['buffered'],1.73205080757j 1.41421356237j 1j 0j (1+0j) (1.41421356237+0j)    # 9.将64位浮点数组视为32位浮点数组for x in np.nditer(a, flags=['buffered'], op_dtypes=['float32'],casting='same_kind'):    print(x)# 0.0 1.0 2.0 3.0 4.0 5.0    # 注意:    # 使用读写或只写操作数时,转换回原始数据类型。一个常见的情况是以64位浮点数实现内部循环,    # 并使用'same_kind'强制转换以允许处理其他浮点类型。在只读模式下,可以提供一个整型数组,    # 读写模式将引发异常,因为转换回数组会违反转换规则。    a = np.arange(6)for x in np.nditer(a, flags=['buffered'], op_flags=['readonly'],                                op_dtypes=['float64'], casting='same_kind'):     x= x / 2.0==================================================================

转载地址:https://chunyou.blog.csdn.net/article/details/84362357 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:numpy 学习汇总20 - 类型转换(比较全 基础学习 tcy)
下一篇:numpy 学习汇总19 - ufunc函数属性,方法,自定义,函数构造数组(详解 基础学习 tcy)

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月30日 04时50分11秒