使用astype(int)将numpy数组转换为整数在Python 3.6上不起作用

问题描述 投票:1回答:1

我有一个大文本文件,每行标签为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。谢谢。

python arrays numpy
1个回答
2
投票

您正在将地图对象传递到数组并尝试转换它。一旦创建了数组,就看看它。它看起来像这样:

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不再返回一个列表,而是一个可迭代的。

© www.soinside.com 2019 - 2024. All rights reserved.