我有一個非常簡單的問題,但不知何故我遇到了麻煩......
我正在用 numpy 創建一個 81x41 字串二維陣列。然后我遍歷這個陣列的所有位置,并想在每個位置放置一個特定的字串。
由于某種原因,它沒有將變數分配給該位置。它仍然是空的。
我怎樣才能做這個簡單的價值分配?我錯過了什么?
我的代碼:
def create_discrete_values(self, threshold: list[int]):
self.map_index_discreet = np.ndarray(shape=(81, 41), dtype=str)
for i in range(81):
for j in range(41):
val = self.map_index[i][j]
discreet_value = None
if val <= threshold[0]:
discreet_value = "Very Low"
elif val <= threshold[1]:
discreet_value = "Low"
elif val <= threshold[2]:
discreet_value = "Moderate"
elif val <= threshold[3]:
discreet_value = "High"
elif val <= threshold[4]:
discreet_value = "Very High"
elif val <= threshold[5]:
discreet_value = "Extreme"
else:
discreet_value = "Very Extreme"
self.map_index_discreet[i][j] = discreet_value
uj5u.com熱心網友回復:
您可以使用dtype='object'which 分配一個指標并允許您將任何內容放入單元格中。如果您關心性能,那么您可能想要使用dtype='U<length>'which 將為 size 的 Unicode 字串分配記憶體<length>。如果你分配一個更長的字串,它會被簡單地切斷(這可能不是你想要的......)。
import numpy as np
map_index_discreet = np.ndarray(shape=(81, 41), dtype='U10')
for i in range(81):
for j in range(41):
map_index_discreet[i][j] = str(i) '_' str(j)
print(map_index_discreet[3][4])
#>>> '3_4'
map_index_discreet[3][4] = 'longer than 10'
print(map_index_discreet[3][4])
#>>> 'longer tha'
dtype='str'不使用某些資料初始化陣列就像定義 a 一樣dtype='U0',正如您發現的那樣,它毫無用處。但是,如果您想初始化一個混合型別的陣列并將其強制轉換為字串陣列,那么這樣做是有意義的,如下所示:
# forcing the array to dtype='str'
np.array(['abc', None, False, 'abdedf'], dtype='str')
#>>> array(['abc', 'None', 'False', 'abdedf'], dtype='<U6')
如您所見,Numpy 查找資料中最長的字串以確定字串陣列的 dtype。
'str'/'U<length>vs.的性能影響在'object'很大程度上取決于您的用例。如果您不處理大量資料,那么您應該堅持使用dtype='object'.
請在此處查看相關的 Numpy 檔案。
uj5u.com熱心網友回復:
你應該使用 dtype=object。使用 dtype=str 創建陣列時,該陣列只能包含長度等于或小于最大元素長度的字串。由于您的陣列為空,因此該長度為 0。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/533781.html
標籤:Python数组麻木的
