根据特定列对numpy数组进行排序

时间:2020-03-27 18:48:54

标签: python numpy sorting

考虑一个如下的numpy数组:

fs.createWriteStream()

此数组包含5个点的x和y坐标。我正在寻找此数组中具有最小y坐标的点。我可以使用

轻松找到它
  coords =   [[34. 22.]
              [11. 38.]
              [22. 56.]
              [23. 22.]
              [86. 30.]]

没问题。除了idx = np.argpartition(coords[:,1],1)[0] pt = coords[idx] 中实际上有两个具有相同的最小y值的点:22

我想要具有较小x值的点,即不是coords,而是[34 22]

这不再是微不足道的。因为我希望能够为任意坐标矩阵找到这样的点。即可能有许多点具有相等的最小y坐标。不止两个。然后,我想根据它们的x坐标对它们进行排序。

我开始用一个丑陋的for循环来解决这个问题,但是失败了。这是我到目前为止所拥有的:

[23 22]

好吧。我可以找到最小的y值。就是这样。我开始相信用numpy-arrays无法解决此任务。

2 个答案:

答案 0 :(得分:2)

您可以使用结构化的 numpy数组和numpy's sort中的order=可选关键字来做到这一点:

>>> x = np.array([(34.,22.),(11., 38.),(22.,56.),(23., 22.),(86.,30.)], dtype = [('x',float),('y',float)])
>>> x
array([(34., 22.), (11., 38.), (22., 56.), (23., 22.), (86., 30.)],
  dtype=[('x', '<f8'), ('y', '<f8')])
>>> x.sort(order = ['y','x'])
>>> x
array([(23., 22.), (34., 22.), (86., 30.), (11., 38.), (22., 56.)],
  dtype=[('x', '<f8'), ('y', '<f8')])

答案 1 :(得分:0)

您可以使用np.lexsort

array([[11., 38.],
       [22., 56.],
       [23., 22.],
       [34., 22.],
       [86., 30.]])

输出:

# generate random num
set.seed(15)
input <- rnorm(100, mean = 10, sd = 3)

# Write to file only if num is greater than threshold
thrshld <- 10
out_dir <- "~/R/tmp/Batch_Saving"

for (i in 1:length(input)) {

  # Create sub-folder if it doesn't exist
  sub_dir = paste0(out_dir, "/Dir_Num_", ceiling(i/10))
  dir.create(sub_dir, showWarnings = F)

  if ( input[i] > thrshld) {

    txt <- paste("The number", signif(input[i], 4), "is greater than", thrshld)

    # Write text to file
    writeLines(text = txt,
               con = paste0(sub_dir, "/file_", i, ".txt") )

  }

}