我有以下源代碼:
npW_x = np.array(my_np_array)
npW_round_111 = np.round(npW_x, decimals=0)
sum_x_111 = np.sum(npW_round_111, axis=1)
np.savetxt("file1.txt"/span>, sum_x_111)
檔案輸出
3.20000000000000e 01
5.500000000000000000e 01
3.300000000000000000e 01
4.900000000000000000e 01
5.200000000000000000e 01
5.500000000000000000e 01
3.800000000000000000e 01
5.200000000000000000e 01
5.100000000000000000e 01
3.100000000000000000e 01
3.100000000000000000e 01
3.200000000000000000e 01
5.100000000000000000e 01
... ... ... ... ... ... ... ... ...。
預期的輸出如下:
3
6
3
5
5 5
6 6
4 4
5 5
5 5
3 3
3 3
3 3
5 5
... ... ... ... ... ... ...。
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
在 [385]: npW_x = np. random.rand(4,5)*10。
...: npW_round_111 = np.round(npW_x, decimals=0)
...: sum_x_111 = np.sum(npW_round_111, axis=1)
...:
在[386]: sum_x_111
Out[386]: array([38., 25., 24., 30.] )
使用默認的fmt進行保存(閱讀并重新閱讀np.savetxt檔案!)
在 [387]: np.savetxt('test',sum_x_111)
在[388]: cat test
3.800000000000000000e 01
2.500000000000000000e 01
2.400000000000000000e 01
3.000000000000000000e 01
用int格式保存:
在 [389]: np.savetxt('test',sum_x_111, fmt='d')
在 [390]: cat test
38: cat test
25
24 24
30 30
在記憶體中轉換為int:
在[391]。在[391]: sum_x_111.astype(int)
Out[391]: array([38, 25, 24, 30] )
uj5u.com熱心網友回復:
你可以使用astype()函式來做這件事
我認為npW_x是需要轉換為int陣列的陣列。
npW_x = np.array(my_np_array)
npW_x = npW_x.astype('int32')
現在,它應該被轉換成一個整數的numpy陣列。
編輯:
我已經添加了完整的代碼,所以你可以嘗試一下
npW_x = np.array(my_np_array)
npW_x = npW_x.astype('int32'/span>)
sum_x_111 = np.sum(npW_x, axis=1)
np.savetxt("file1.txt"/span>, sum_x_111)
希望它能解決你的問題。
uj5u.com熱心網友回復:
arr = np.asarray([3.20000000000000e 01,
5.500000000000000000e 01,
3.300000000000000000e 01,
4.900000000000000000e 01,
5.200000000000000000e 01,
5.500000000000000000e 01,
3.800000000000000000e 01,
5.200000000000000000e 01,
5.100000000000000000e 01,
3.100000000000000000e 01,
3.100000000000000000e 01,
3.200000000000000000e 01,
5.100000000000000000e 01])
arr
array([32. , 55. , 33. , 49. , 52. , 55. , 38. , 52. , 51. , 31. , 31. 。
32. , 5.1] )
np.round(np.where(arr/10, arr/10, arr) ).astype('int')
get
array([3, 6, 3, 5, 5, 6, 4, 5, 5, 3, 3, 3, 5] )
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/326859.html
標籤:
上一篇:定義陣列而不分配它
