有数字数组作为输入: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())