简体   繁体   English

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

[英]Converting a numpy array to integer with astype(int) does not work on Python 3.6

I have a large text file with labels 0 or 1 in each line like this:我有一个大文本文件,每行标签为 0 或 1,如下所示:

1
0
0
1
...

I load it, convert it into a numpy array, and then I want to convert the array into dtype=int64 (as I assume these are strings).我加载它,将其转换为一个 numpy 数组,然后我想将数组转换为dtype=int64 (因为我假设这些是字符串)。 I do it like this:我这样做:

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)

It works fine in Python 2.7, and I can work on the array later with my code, but for now I'm stuck with Python 3.6 and when I ran my code, I get an error:它在 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'

Can anyone help me figure out what is going on here and how to get it to work on Python 3.6?谁能帮我弄清楚这里发生了什么以及如何让它在 Python 3.6 上工作? I also tried:我也试过:

labels_encoded = np.int_(labels_encoded)

but I got the same error.但我遇到了同样的错误。 I'm using numpy version 1.13.3.我正在使用 numpy 版本 1.13.3。 Thanks.谢谢。

You are passing a map object into the array and trying to convert it.您正在将地图对象传递到数组中并尝试对其进行转换。 Take a look at the array once it has been created.创建数组后查看它。 It looks like this:它看起来像这样:

array(<map object at 0x127680cf8>, dtype=object)

Try using list(map(...)) instead.尝试使用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])

If you are just making the jump from 2.7 you should note that map no longer returns a list but an iterable.如果你只是从 2.7 开始跳转,你应该注意到map不再返回一个列表而是一个可迭代的。

I had same problem.我有同样的问题。 My code did not work:我的代码不起作用:

train_size = np.ceil(len(dataset) * 0.8).astype(int)
print(type(train_size))  # --> numpy.int32

But this works great:但这很好用:

train_size = int(np.ceil(len(dataset) * 0.8))
print(type(train_size))  # --> int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM