所以我在一个单一的平面数组中有大量数据,这些数据被分组为大小不规则的块。这些块的大小在另一个数组中给出。我需要做的是根据第三个索引数组重新排列块(想想花式索引)
这些块总是 >= 3 长,通常是 4,但技术上是无界的,所以填充到最大长度和掩码是不可行的。另外,由于技术原因,我只能访问 numpy,所以没有像 scipy 或 pandas 这样的东西。
为了更容易阅读,这个例子中的数据很容易分组。在真实数据中,数字可以是任何东西,并且不遵循这种模式。
[编辑] 更新了较少混淆的数据
data = np.array([1,2,3,4, 11,12,13, 21,22,23,24, 31,32,33,34, 41,42,43, 51,52,53,54])
chunkSizes = np.array([4, 3, 4, 4, 3, 4])
newOrder = np.array([0, 5, 4, 5, 2, 1])
在这种情况下的预期输出将是
np.array([1,2,3,4, 51,52,53,54, 41,42,43, 51,52,53,54, 21,22,23,24, 11,12,13])
由于真实数据可能长达数百万,我希望有某种 numpy 魔法可以在没有 python 循环的情况下做到这一点。
最佳答案
方法#1
这是一个基于创建常规数组和掩码的矢量化 -
def chunk_rearrange(data, chunkSizes, newOrder):
m = chunkSizes[:,None] > np.arange(chunkSizes.max())
d1 = np.empty(m.shape, dtype=data.dtype)
d1[m] = data
return d1[newOrder][m[newOrder]]
给定样本的输出 -
In [4]: chunk_rearrange(data, chunkSizes, newOrder)
Out[4]: array([0, 0, 0, 0, 5, 5, 5, 5, 4, 4, 4, 5, 5, 5, 5, 2, 2, 2, 2, 1, 1, 1])
方法#2
另一种基于
cumsum
的矢量化并且对于那些非常参差不齐的块大小来说占用空间更小 -def chunk_rearrange_cumsum(data, chunkSizes, newOrder):
# Setup ID array that will hold specific values at those interval starts,
# such that a final cumsum would lead us to the indices which when indexed
# by the input array gives us the re-arranged o/p
idar = np.ones(len(data), dtype=int)
# New chunk lengths
newlens = chunkSizes[newOrder]
# Original chunk intervals
c = np.r_[0,chunkSizes[:-1].cumsum()]
# Indices from original order that form the interval starts in new arrangement
d1 = c[newOrder]
# Starts of chunks in new arrangement where those from d1 are to be assigned
c2 = np.r_[0,newlens[:-1].cumsum()]
# Offset required for the starts in new arrangement for final cumsum to work
diffs = np.diff(d1)+1-np.diff(c2)
idar[c2[1:]] = diffs
idar[0] = d1[0]
# Final cumsum and indexing leads to desired new arrangement
out = data[idar.cumsum()]
return out
关于python - 如何快速对扁平化的 "jagged"numpy 数组重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62291572/