Python 将 numpy 字符串数组转换为 int 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21451776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:53:01  来源:igfitidea点击:

convert numpy string array into int array

pythonnumpy

提问by veena



I have a numpy.ndarray

我有一个 numpy.ndarray

a = [['-0.99' '' '0.56' ..., '0.56' '-2.02' '-0.96']]

how to convert it to int?

如何将其转换为int?

output :

输出 :

a = [[-0.99 0.0 0.56 ..., 0.56 -2.02 -0.96]]

I want 0.0 in place of blank ''

我想要 0.0 代替空白 ''

回答by FallenAngel

That is a pure python solution and it produces a list.

这是一个纯 python 解决方案,它生成一个list.

With simple python operations, you can map inner list with float. That will convert all string elements to float and assign it as the zero indexed item of your list.

通过简单的python操作,你可以用float映射内部列表。这会将所有字符串元素转换为 float 并将其分配为列表的零索引项。

a = [['-0.99' , '0.56' , '0.56' , '0.56', '-2.02' , '-0.96']]

a[0] = map(float, a[0])

print a
[[-0.99, 0.56, 0.56, 0.56, -2.02, -0.96]]

Update: Try the following

更新:尝试以下操作

a = [['-0.99' , '0.56' , '0.56' , '0.56', '-2.02' , '-0.96', '', 'nan']]
for _position, _value in enumerate(a[0]):
    try:
        _new_value = float(_value)
    except ValueError:
        _new_value = 0.0
    a[0][_position] = _new_value

[[-0.99, 0.56, 0.56, 0.56, -2.02, -0.96, 0.0, nan]]

It enumerates the objects in the list and try to parse them to float, if it fails, then replace it with 0.0

它枚举列表中的对象并尝试将它们解析为float,如果失败,则将其替换为0.0

回答by abudis

import numpy as np

a = np.array([['-0.99', '', '0.56', '0.56', '-2.02', '-0.96']])
a[a == ''] = 0.0
a = a.astype(np.float)

Result is:

结果是:

[[-0.99  0.    0.56  0.56 -2.02 -0.96]]

Your values are floats, not integers. It is not clear if you want a list of lists or a numpy array as your end result. You can easily get a list of lists like this:

您的值是浮点数,而不是整数。目前尚不清楚您想要一个列表列表还是一个 numpy 数组作为最终结果。您可以轻松获得如下列表:

a = a.tolist()

Result:

结果:

[[-0.99, 0.0, 0.56, 0.56, -2.02, -0.96]]