[英]Converting a numpy array to integer with astype(int) does not work on Python 3.6
我有一個大文本文件,每行標簽為 0 或 1,如下所示:
1
0
0
1
...
我加載它,將其轉換為一個 numpy 數組,然后我想將數組轉換為dtype=int64
(因為我假設這些是字符串)。 我這樣做:
def load_data(infile):
text_file = open(infile,'r')
text = text_file.readlines()
text = map(str.strip,text)
return text
labels = load_data('labels.txt')
labels_encoded = np.array(labels)
labels_encoded = labels_encoded.astype(int)
它在 Python 2.7 中運行良好,稍后我可以使用我的代碼處理數組,但現在我堅持使用 Python 3.6,當我運行我的代碼時,出現錯誤:
Traceback (most recent call last):
File "dText.py", line 77, in <module>
labels_encoded = labels_encoded.astype(int)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'map'
誰能幫我弄清楚這里發生了什么以及如何讓它在 Python 3.6 上工作? 我也試過:
labels_encoded = np.int_(labels_encoded)
但我遇到了同樣的錯誤。 我正在使用 numpy 版本 1.13.3。 謝謝。
您正在將地圖對象傳遞到數組中並嘗試對其進行轉換。 創建數組后查看它。 它看起來像這樣:
array(<map object at 0x127680cf8>, dtype=object)
嘗試使用list(map(...))
代替。
def load_data(infile):
text_file = open(infile,'r')
text = text_file.readlines()
text = list(map(str.strip,text))
return text
labels = load_data('labels.txt')
labels_encoded = np.array(labels)
labels_encoded = labels_encoded.astype(int)
labels_encoded
array([1, 0, 1, 0])
如果你只是從 2.7 開始跳轉,你應該注意到map
不再返回一個列表而是一個可迭代的。
我有同樣的問題。 我的代碼不起作用:
train_size = np.ceil(len(dataset) * 0.8).astype(int)
print(type(train_size)) # --> numpy.int32
但這很好用:
train_size = int(np.ceil(len(dataset) * 0.8))
print(type(train_size)) # --> int
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.