[英]extract values from list with the help of another list with condition in python
[英]Change values in array (condition) with values from another list
我有以下清單:
indices
>>> [21, 43, 58, 64, 88, 104, 113, 115, 120]
我希望從我擁有的3D數組“ q”中將列表-1(因此20、42、57等)中這些值的所有出現都清零。
我已經嘗試過列表推導,for和if循環(請參見下文),但是我總是遇到以下錯誤:
ValueError:具有多個元素的數組的真值不明確。 使用a.any()或a.all()
我無法解決此問題。
任何幫助都將是驚人的!
>>> for b in q:
... for u in indices:
... if b==u:
... b==0
>>> for u in indices:
... q = [0 if x==u else x for x in q]
我認為這是一種簡短有效的方法:
b= b*np.logical_not(np.reshape(np.in1d(b,indices),b.shape))
與np.in1d(),我們有一個布爾陣列,具有真,其中B中的元件處於indices
。 我們將其重塑為b
,然后取反,以便在將b
設為零的地方有False
(或者,如果您願意,則為0)。 只需將此矩陣元素乘以b,就可以得到
它具有可用於1D,2D,3D等數組的優點
我嘗試了這個,對我有用:
>>> arr_2D = [3,4,5,6]
>>> arr_3D = [[3,4,5,6],[2,3,4,5],[4,5,6,7,8,8]]
>>> for el in arr_2D:
... for x in arr_3D:
... for y in x:
... if y == el - 1:
... x.remove(y)
...
>>> arr_3D
[[6], [], [6, 7, 8, 8]]
在這種情況下,用列表理解的接縫來完成它可能是過大的。
或歸零而不是刪除
>>> for el in arr_2D:
... for x in range(len(arr_3D)):
... for y in range(len(arr_3D[x])):
... if arr_3D[x][y] == el - 1:
... arr_3D[x][y] = 0
...
>>> arr_3D
[[0, 0, 0, 6], [0, 0, 0, 0], [0, 0, 6, 7, 8, 8]]
這是列表理解:
zero_out = lambda arr_2D, arr_3D: [[0 if x in [el-1 for el in arr_2D] else x for x in y] for y in arr_3D]
這個怎么樣?
indices = range(1, 10)
>>[1, 2, 3, 4, 5, 6, 7, 8, 9]
q = np.arange(12).reshape(2,2,3)
array([[[ 0, 1, 2],
[ 3, 4, 5]],
[[ 6, 7, 8],
[ 9, 10, 11]]])
def zeroed(row):
new_indices = map(lambda x: x-1, indices)
nrow = [0 if elem in new_indices else elem for elem in row]
return now
np.apply_along_axis(zeroed, 1, q)
array([[[ 0, 0, 0],
[ 0, 0, 0]],
[[ 0, 0, 0],
[ 9, 10, 11]]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.