在不使用for-loop 或while-loop 的情況下,您將如何在 numpy 中執行此操作,并且如果可能,在執行時間方面使用最快的方法來執行此操作。
它類似于“如果特定列和行中的值高于 20,則分配先前的值”。
(我在這種情況下使用第 2 列)
a = np.random.randint(1,50, size=(10,5))
print(a)
print('--------------')
for index in range(len(a)):
if (a[index][2] > 20) and index>0:
a[index][2]=a[index-1][2]
print(a)
[[21 24 | 7| 10 12]
[ 4 36 |42| 4 48]
[37 43 |36| 30 13]
[39 10 |45| 45 15]
[46 48 |25| 39 20]
[ 2 33 |37| 38 28]
[23 36 |14| 29 33]
[17 24 |47| 4 9]
[45 9 |42| 34 3]
[13 49 |26| 14 34]]
--------------
[[21 24 | 7| 10 12]
[ 4 36 | 7| 4 48]
[37 43 | 7| 30 13]
[39 10 | 7| 45 15]
[46 48 | 7| 39 20]
[ 2 33 | 7| 38 28]
[23 36 |14| 29 33]
[17 24 |14| 4 9]
[45 9 |14| 34 3]
[13 49 |14| 14 34]]
uj5u.com熱心網友回復:
由于值是重復的,您可以使用 np.repeat
arr = a[:, 2]
cutoff_idx = np.flatnonzero(arr<=20)
vals = arr[cutoff_idx]
counts = np.diff(cutoff_idx, append=len(arr))
if len(cutoff_idx) > 0:
n = cutoff_idx[0]
a[:n, 2] = arr[:n] #this is a custom approach since there's no info
a[n:, 2] = np.repeat(vals, counts)
uj5u.com熱心網友回復:
以下代碼將得到結果:
spec_col = a[:, 2]
cond = np.where(a[:, 2] <= 20)[0]
diff = np.diff(cond, append=len(spec_col))
cond_vals = np.take(spec_col, cond)
repeated_arr = np.repeat(cond_vals, diff)
spec_col[np.where(a[:, 2] <= 20)[0][0]:] = repeated_arr
print(a)
它會卡死,如果有沒有任何values < 20的spec_col,二人于np.where自然,這可以很容易地進行處理try-except的方法:
try:
spec_col = a[:, 2]
cond = np.where(a[:, 2] <= 20)[0]
diff = np.diff(cond, append=len(spec_col))
cond_vals = np.take(spec_col, cond)
repeated_arr = np.repeat(cond_vals, diff)
spec_col[np.where(a[:, 2] <= 20)[0][0]:] = repeated_arr
print(a)
except:
a[:, 2] = a[0, 2] # or any values
print(a)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/367995.html
