[numpy]去掉每行的最[大/小]值求mean/sum

import numpy as np

np.random.seed(512)
x = np.random.randn(12,5)

x.shape

方案一

  • 只能去掉n个最值

# 去掉最小的*一个* mean,sum,...
Mean = np.sort(x,axis=1)[:,1:].mean(axis=1)
Sum = np.sort(x,axis=1)[:,1:].sum(axis=1)

# 去掉最大的*一个*
Mean = np.sort(x,axis=1)[:,:-1].mean(axis=1)
Sum = np.sort(x,axis=1)[:,:-1].sum(axis=1)

方案二

  • numpy==1.23.5

  • 可能不止一个最小/大值

# >minValue的求mean,sum,...
Mean = x.mean(axis=1, where=x > x.min(axis=1, keepdims=True))
Sum = x.sum(axis=1, where=x > x.min(axis=1, keepdims=True))

# 

验证

# >minValue
np.allclose(x[0, [0, 1, 3, 4]].mean(), Mean[0])

# 

你可能感兴趣的:(#,numpy,python)