[英]Numpy: Efficient elements of array A in terms of the indices of matching elements of array B
[英]Matching elements in numpy array
我有兩個numpy數組。 第一個Z1大約長30萬行,寬3列。 第二個Z2大約為200,000行300列。 Z1和Z2的每一行都有一個標識號(10位數字)。 Z2包含Z1中項目的子集,我想基於10位標識號將Z2中的行與其Z1中的伙伴進行匹配,然后從Z1中提取第2列和第3列,並將它們插入到Z2中的末尾他們適當的行。
Z1和Z2都沒有任何特定順序。
我想到的唯一方法是遍歷數組,這需要幾個小時。 在Python中有更好的方法嗎?
謝謝!
我從您的問題中了解到10位標識符存儲在第1列中,對嗎?
這是不是很容易做到,很多間接的事情,但最終unsorted_insert
擁有其中的行號Z1
的每個標識符Z2
是
sort_idx = np.argsort(Z1[:, 0])
sorted_insert = np.searchsorted(Z1[:, 0], Z2[:, 0], sorter=sort_idx)
# The following is equivalent to unsorted_insert = sort_idx[sorted_insert] but faster
unsorted_insert = np.take(sort_idx, sorted_insert)
因此,現在我們要做的就是獲取這些行的最后兩列,並將它們堆疊到Z2
數組中:
new_Z2 = np.hstack((Z2, Z1[unsorted_insert, 1:]))
一個沒有問題的完整示例:
import numpy as np
z1_rows, z1_cols = 300000, 3
z2_rows, z2_cols = 200000, 300
z1 = np.arange(z1_rows*z1_cols).reshape(z1_rows, z1_cols)
z2 = np.random.randint(10000, size=(z2_rows, z2_cols))
z2[:, 0] = z1[np.random.randint(z1_rows, size=(z2_rows,)), 0]
sort_idx = np.argsort(z1[:, 0])
sorted_insert = np.searchsorted(z1[:, 0], z2[:, 0], sorter=sort_idx)
# The following is equivalent to unsorted_insert = sort_idx[sorted_insert] but faster
unsorted_insert = np.take(sort_idx, sorted_insert)
new_z2 = np.hstack((z2, z1[unsorted_insert, 1:]))
尚未計時,但整個過程似乎在幾秒鍾內完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.