我们得到了两个包含数字的文本文件,我们需要使用 numpy.loadtxt
加载它们,然后找到文本文件中正数的平均值。
这是我迄今为止尝试过的:
A = np.loadtxt('A.txt')
B = np.loadtxt('B.txt')
A_mean = np.mean(np.where(A>0))
B_mean = np.mean(np.where(B>0))
print(f'A={A_mean}')
print(f'B={B_mean}')
我知道这显然是错误的,因为它似乎返回索引号的平均值,而不是值。如何获得实际值的平均值?
最佳答案
np.where(A > 0)
返回您注意到的 A > 0
的索引。要获取 A
的元素,请使用索引:np.mean(A[np.where(A > 0)])
。
但是等等,A > 0
是一个 bool 数组,在满足条件的每个元素中都有 True
,而在其他地方则有 False
。这样的数组称为“掩码”,也可用于索引:
A[A > 0].mean()
关于python - 如何获取 numpy 数组中正数的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71213528/