我有以下陣列,我想根據它在字典中對應的內容來替換其中的值。
大批:
[[ 0. -1. 1. 1.]
[ 0. 1. -2. -3.]
[-1. 1. 1. -5.]
[-3. -1. -1. 2.]
[-5. 2. -4. -2.]
[-1. -3. -1. 2.]
[ 0. 1. -3. 1.]
[-2. -3. 0. -2.]
[-2. -2. 1. -6.]
[-0. -2. 2. -0.]]
字典:
dict = {-13: 13.0,
-12: 9.375,
-11: 9.4,
-10: 8.6,
-9: 8.3,
-8: 7.8,
-7: 7.1,
-6: 6.4,
-5: 5.8,
-4: 5.2,
-3: 4.6,
-2: 4.0,
-1: 3.6,
0: 3.2,
1: 2.8,
2: 2.5,
3: 2.2,
4: 2.0,
5: 1.8,
6: 1.6}
例如,陣列中的任何 0 都將替換為 3.2,陣列中的任何 -1 都將替換為 3.6,依此類推。原始陣列為 120x10000x4,因此任何速度優化都是理想的。
提前感謝您的幫助!
uj5u.com熱心網友回復:
我認為這回答了你的問題。您可以查看此以獲取更多資訊。
import numpy as np
from numpy import copy
a = np.array([[ 0., -1., 1., 1.],[ 0., 1., -2., -3.],[-1., 1., 1., -5.],[-3., -1., -1., 2.],[-5., 2., -4., -2.],[-1., -3., -1., 2.],[ 0., 1., -3., 1.],[-2., -3., 0., -2.],[-2., -2., 1., -6.],[-0., -2., 2., -0.]]) # You need to save this as `np.array`.
d = {-13: 13.0,-12: 9.375,-11: 9.4,-10: 8.6,-9: 8.3,-8: 7.8,-7: 7.1,-6: 6.4,-5: 5.8,-4: 5.2,-3: 4.6,-2: 4.0,-1: 3.6,0: 3.2,1: 2.8,2: 2.5,3: 2.2,4: 2.0,5: 1.8,6: 1.6}
new_a = copy(a) # This will create a copy of the `a` array. So, you can apply operations on it and not on original data.
for key, value in d.items(): # Taking key and values from dictionary.
new_a[a==key] = value # Matching the items where the item in array is same as in the dictionary. Setting it's value to the value of dictionary
print(new_a)
輸出:
[[3.2 3.6 2.8 2.8]
[3.2 2.8 4. 4.6]
[3.6 2.8 2.8 5.8]
[4.6 3.6 3.6 2.5]
[5.8 2.5 5.2 4. ]
[3.6 4.6 3.6 2.5]
[3.2 2.8 4.6 2.8]
[4. 4.6 3.2 4. ]
[4. 4. 2.8 6.4]
[3.2 4. 2.5 3.2]]
uj5u.com熱心網友回復:
這是執行您所要求的代碼:
import numpy as np
a = [[ 0., -1., 1., 1.],
[ 0., 1., -2., -3.],
[-1., 1., 1., -5.],
[-3., -1., -1., 2.],
[-5., 2., -4., -2.],
[-1., -3., -1., 2.],
[ 0., 1., -3., 1.],
[-2., -3., 0., -2.],
[-2., -2., 1., -6.],
[-0., -2., 2., -0.]]
d = {-13: 13.0,
-12: 9.375,
-11: 9.4,
-10: 8.6,
-9: 8.3,
-8: 7.8,
-7: 7.1,
-6: 6.4,
-5: 5.8,
-4: 5.2,
-3: 4.6,
-2: 4.0,
-1: 3.6,
0: 3.2,
1: 2.8,
2: 2.5,
3: 2.2,
4: 2.0,
5: 1.8,
6: 1.6}
x = np.array(a)
y = np.copy(x)
for k, v in d.items():
x[y == k] = v
print(x)
我已將dict問題替換為d以避免使用dict內置資料型別的名稱作為變數名,這可能會導致同一模塊中的其他地方出現問題。
這是示例輸出:
[[3.2 3.6 2.8 2.8]
[3.2 2.8 4. 4.6]
[3.6 2.8 2.8 5.8]
[4.6 3.6 3.6 2.5]
[5.8 2.5 5.2 4. ]
[3.6 4.6 3.6 2.5]
[3.2 2.8 4.6 2.8]
[4. 4.6 3.2 4. ]
[4. 4. 2.8 6.4]
[3.2 4. 2.5 3.2]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436238.html
下一篇:使用Python進行最近鄰選擇
