numpy迭代

文章介绍了numpy库中nditer函数的基本用法,包括如何在多维数组上迭代,以及如何设置op_flags进行只读或读写操作。还讨论了C_index、F_index和external_loop等迭代器标志在不同情况下的应用。
摘要由CSDN通过智能技术生成

numpy学习专题

九、numpy迭代

迭代

numpy.nidter基本使用
它是一个有效的多维迭代器对象,可以用在数组上迭代。数组的每个元素可使用python的标准iterator接口来访问
import numpy as np
a=np.arange(12).reshape(3,4)
print(a)
print("\n")
for x in np.nditer(a):
    print(x,end=", ")
print("")
import numpy as np
a=np.arange(12).reshape(3,4)
print(a)
print("\n")
for x in np.nditer(a):
    print(x,end=", ")
print("\n")
print(a.T,"\n")
for x in np.nditer(a.T):
    print(x,end=", ")
print("\n")
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]


0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 

[[ 0  4  8]
 [ 1  5  9]
 [ 2  6 10]
 [ 3  7 11]] 

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 
b = a.T.copy(order = "C")
print(b)
print("\n")
for i in np.nditer(b):
    print(i,end=", ")
print("\n")
[[ 0  8 16]
 [ 2 10 18]
 [ 4 12 20]
 [ 6 14 22]]


0, 8, 16, 2, 10, 18, 4, 12, 20, 6, 14, 22, 
b = a.T.copy(order = "F")
print(b)
print("\n")
for i in np.nditer(b):
    print(i,end=", ")
print("\n")
[[ 0  4  8]
 [ 1  5  9]
 [ 2  6 10]
 [ 3  7 11]]


0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 
b = a.T.copy(order ="C")
print(b)
print("\n")
for i in np.nditer(b,order ="C"):
    print(i,end=", ")
print("\n")
for i in np.nditer(b,order = "F"):
    print(i,end=", ")
print("\n")

[[ 0  4  8]
 [ 1  5  9]
 [ 2  6 10]
 [ 3  7 11]]


0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11, 

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 
迭代过程中,数组是只读的,如果想对ndarray数组的元素进行修改,则需将op_flags进行修改 即:op_flags = [“readwrite”]
b = a.T.copy(order ="C")
print(b)
print("\n")
for i in np.nditer(b,order ="C",op_flags = ["readwrite"]):
    i*=2
print(b)

for i in np.nditer(a,order = "F",op_flags = ["readwrite"]):
    i[...]=i*2
print("\n",b)

外部循环

nditer类的构造器拥有flags参数,可以接受下列值
                 说明

c_index            可以跟踪C顺序的索引
    
f_index            可以跟踪Fortran顺序的索引
    
multi_index        每次迭代可以跟踪一种索引类型
    
external_loop      给出的值具有多个值的一维数组,而不是零维数组

迭代器遍历对应每列的一维数组

import numpy as np
arr = np.arange(12).reshape(4,3)
print(arr,"\n")
for x in np.nditer(arr,flags = ["external_loop"],order = "F"):
    print(x,end=", ")
print("\n")

for x in np.nditer(arr,flags = ["external_loop"]):
    print(x,end=", ")
print("\n")

for x in np.nditer(arr,flags =["f_index"]):
    print(x,end=", ")
print("\n")

for x in np.nditer(arr,flags = ["c_index"]):
    print(x,end=", ")
print("\n")
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]] 

[0 3 6 9], [ 1  4  7 10], [ 2  5  8 11], 

[ 0  1  2  3  4  5  6  7  8  9 10 11], 

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 

一定要支持作者哦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值