我试图从包含整数的数组中计算信息,但是当我进行计算时,结果是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))发布于 2021-10-23 15:49:05
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有int数据类型,那么ham_fields也有。你可以用另一个任务来改变这一点。
ham_fields = ham_fields.astype(float)ham_sum与派生它的ham_fields具有相同的dtype。
将浮点数分配给int数据类型数组的元素不会更改数据类型。
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变量。这是一个新的赋值(而不是修改),因此保留了浮动数据类型。或者,为了清楚起见,将其分配给一个新的变量名。
发布于 2021-10-23 15:16:08
您可以在计算后使用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://stackoverflow.com/questions/69689289
复制相似问题