我正在嘗試從包含整數的陣列中計算資訊,但是當我進行計算時,結果是 foat 的。如何更改 ndarry 以接受 0.xxx 數字作為輸入。目前我只得到0。這是我一直試圖開始作業的代碼:
ham_fields = np.array([], dtype=float) # dtype specifies the type of the elements
ham_total = np.array([], dtype=float) # dtype specifies the type of the elements
ham_fields = data[data[:, 0] == 0] # All the first column of the dataset doing a check if they are true or false
ham_sum = np.delete((ham_fields.sum(0)),0) # Boolean indices are treated as a mask of elements to remove none Ham items
ham_total = np.sum(ham_sum)
ham_len = len(ham_sum)
for i in range(ham_len):
ham_sum[i] = (ham_sum[i] self.alpha) / (ham_total (ham_len * self.alpha))
uj5u.com熱心網友回復:
ham_fields = np.array([], dtype=float)
ham_fields = data[data[:, 0] == 0]
ham_sum = np.delete((ham_fields.sum(0)),0)
這一行將一個新的陣列物件分配給ham_fields。第一個任務對你沒有任何幫助。在 Python 中,變數不是在開始時宣告的。
如果data有intdtype,那么也有ham_fields。你可以用另一個作業來改變它
ham_fields = ham_fields.astype(float)
ham_sum有相同dtype的ham_fields,從它的派生。
將浮點數分配給intdtype 陣列的元素不會更改 dtype。
for i in range(ham_len):
ham_sum[i] = (ham_sum[i] self.alpha) / (ham_total (ham_len * self.alpha))
如果self.alpha,ham_total是標量,那么你應該能夠做到
ham_sum = (ham_sum self.alpha)/(ham_toal (ham_len * self.alpha))
這將創建一個新陣列,它將是浮點數,并將其分配給ham_sum變數。這是一個新的分配(不是修改),因此保留了 float dtype。或者為了清楚起見,將其分配給一個新的變數名稱。
uj5u.com熱心網友回復:
您可以在計算后使用 astype(int) 將其轉換為 int 陣列
import numpy as np
array1 = np.array([1, 2, 3])
print(array1.dtype)
#output: int64
array2 = np.array([2, 3, 4])
print(array2.dtype)
#output: int64
array3 = array1 / array2
print(array3.dtype)
#output: float64
array4 = array3.astype(int)
print(array3.dtype)
#output: int64
您還可以通過使用括號在計算中執行此操作:
array3 = (array1 / array2).astype(int)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/334121.html
上一篇:如何根據點符號和“型別”屬性將平面陣列轉換為樹陣列?
下一篇:對鍵不一致的字典串列進行排序
