[英]How to make rows and columns into variables in Python numpy?
我需要计算其索引(row + column) % 5
的平均值。 我了解如何调用特定索引,但我无法将行和列定义为变量 i 和 j,以便我可以创建需要满足的条件。
data = np.random.normal(1, 0.5, size=(8, 9)) #generate an array
a() # empty list where the values whose indices meet the condition are going to be saved
i, j = np.ix_(data) <- does not work
for x in data
if i + j % 5:
a.add(x)
您的问题不清楚(row + column) % 5
要求。 但是假设您想要(row + column) % 5 == 0
的值,您可以构建索引器并利用高级索引。
np.random.seed(1)
data = np.random.normal(1, 0.5, size=(8, 9)) #generate an array
idx = [(i, j)
for i in range(data.shape[0])
for j in range(data.shape[1])
if (i + j) % 5 == 0
]
x = [e[0] for e in idx]
y = [e[1] for e in idx]
filtered = data[(x, y)] # advanced indexing
result = mean(filtered)
print(data)
print(idx)
print(filtered)
print(result)
输出
[[ 1.81217268 0.69412179 0.73591412 0.46351569 1.43270381 -0.15076935
1.87240588 0.61939655 1.15951955]
[ 0.87531481 1.73105397 -0.03007035 0.8387914 0.80797282 1.56688472
0.45005437 0.9137859 0.56107079]
[ 1.02110687 1.29140761 0.44969041 1.57236185 1.45079536 1.25124717
1.45042797 0.65813607 0.93855489]
[ 0.53211528 0.86605596 1.26517773 0.65416962 0.80162324 0.65641365
0.57739718 0.66437693 0.9936677 ]
[ 0.44134483 1.11720785 1.82990109 1.37102208 0.90408222 0.55618552
0.62642085 1.8462273 1.02540388]
[ 0.68150218 1.09545774 2.05012757 1.06007948 1.30860155 1.15008516
0.82387508 0.4287409 0.82532864]
[ 0.89555288 1.2933116 1.41949171 1.46555104 1.14279366 1.44257058
0.62280103 1.62643408 1.25646491]
[ 0.85095358 1.24425907 0.96221414 1.56581469 1.75990841 2.0927877
0.30175183 0.2779431 0.74776707]]
[(0, 0), (0, 5), (1, 4), (2, 3), (2, 8), (3, 2), (3, 7), (4, 1), (4, 6), (5, 0), (5, 5), (6, 4), (7, 3), (7, 8)]
[ 1.81217268 -0.15076935 0.80797282 1.57236185 0.93855489 1.26517773
0.66437693 1.11720785 0.62642085 0.68150218 1.15008516 1.14279366
1.56581469 0.74776707]
0.9958170735553157
另一个解决方案,更容易遵循:
import numpy as np
np.random.seed(1)
data = np.random.normal(1, 0.5, size=(8, 9))
a = []
for ix,iy in np.ndindex(data.shape):
if (ix+iy) % 5 == 0:
a.append(data[ix, iy])
mean = np.array(a).mean()
print(a)
print(mean)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.