根据分位数的接近程度更改数组的值

  • 本文关键字:程度更 数组 接近 python
  • 更新时间 :
  • 英文 :


有数字数组作为输入:1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 123, 123, 154, 243, 213, 1231241237, 1231241236, 1231241239

我想看到的输出:1, 1, 1, 1, 1, 1 ,1 ,1, 1, 1, 1, 1, 1, 154, 154, 154, 154, 154, 1231241239, 1231241239, 1231241239

R中有我想要的代码。我需要把这个翻译成python:

# https://stackoverflow.com/questions/67766337/change-the-values-of-a-vector-based-on-proximity-of-quantile-numbers
vector <- c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 123, 123, 154, 243, 213, 1231241237, 1231241236, 1231241239)
q <- quantile(vector, probs = c(0, 0.25, 0.5, 0.75, 1)) %>% unname()
q[sapply(vector, function(x) which.min(abs(x - q)))]
# 1, 1, 1, 1, 1, 1 ,1 ,1, 1, 1, 1, 1, 1, 154, 154, 154, 154, 154, 1231241239, 1231241239, 1231241239
data = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 123, 123, 154, 243, 213, 1231241237, 1231241236, 1231241239])

quantiles = np.quantile(data, [0, 0.25, 0.5, 0.75, 1])

print((quantiles[abs(data[None, :] - quantiles[:, None]).argmin(axis=0)]).tolist())

相关内容

  • 没有找到相关文章

最新更新