我嘗試在 StackOverflow 上廣泛尋找這個問題,但我找不到任何東西。我正在無人機上撰寫一些演算法,這些演算法需要快速,以便我的系統不會出現故障。
我有一組要點,如下所示:
In: points = np.array( [[ 0 10 10], [ 4 8 8], [14 14 14], [16 19 19]] )
Out: points:
[[ 0 10 10]
[ 4 8 8]
[14 14 14]
[16 19 19]]
我正在努力實作以下目標:
new_points:
[[ 0 10 10]
[ 0 10 10]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[ 4 8 8]
[ 4 8 8]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[14 14 14]
[14 14 14]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[16 19 19]
[16 19 19]]
每個點沿軸 = 0 重復一次,然后在這些點之間插入 6 行(可以是任意數量)零行。如果它更容易,我不介意最后一點之后是否也有零。
我嘗試使用np.concatenate()、np.insert()和np.repeat()來執行此操作,但是我只能在不需要的位置插入一行零。例如,這是我嘗試插入的內容:
In: np.insert(points, np.arange(1,len(points)), 0, axis = 0)
Out: new_points:
[[ 0 10 10]
[ 0 0 0]
[ 0 10 10]
[ 0 0 0]
[ 4 8 8]
[ 0 0 0]
[ 4 8 8]
[ 0 0 0]
[14 14 14]
[ 0 0 0]
[14 14 14]
[ 0 0 0]
[16 19 19]
[ 0 0 0]]
我無法連接成正確的形狀。這篇StackOverflow 帖子展示了 np.concatenate() 如何更快,所以這就是我嘗試它的原因。我正在嘗試僅使用 numpy 。有小費嗎?
uj5u.com熱心網友回復:
首先創建一個零陣列,然后為其賦值points:
new_points = np.zeros((points.shape[0] * 8 - 6, points.shape[1]))
new_points[::8] = points
new_points[1::8] = points
new_points
array([[ 0., 10., 10.],
[ 0., 10., 10.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 4., 8., 8.],
[ 4., 8., 8.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[14., 14., 14.],
[14., 14., 14.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[16., 19., 19.],
[16., 19., 19.]])
uj5u.com熱心網友回復:
np.c_使用and的一種方法np.tile:
x,y = points.shape
n1 = 2 # number of times to duplicates the existing rows
n2 = 6 # number of zeros' rows to insert in between
# n1 times existing data # n2 times zeros # to original shape
out = np.c_[np.tile(points, (1,n1)), np.zeros((x, y*n2))].reshape(-1,y)[:-n2]
輸出:
array([[ 0., 10., 10.],
[ 0., 10., 10.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 4., 8., 8.],
[ 4., 8., 8.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[14., 14., 14.],
[14., 14., 14.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[16., 19., 19.],
[16., 19., 19.]])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/429850.html
