Convert numpy string array to int array


I have numpy.ndarray

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

how to convert it to int?

output:

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

I want 0.0 instead of empty. ''

+4
source share
2 answers
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:

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

Your values ​​are floats, not integers. It's not clear if you need a list of lists or a numpy array as the end result. You can easily get a list of such lists:

a = a.tolist()

Result:

[[-0.99, 0.0, 0.56, 0.56, -2.02, -0.96]]
+6
source

This is a pure python solution and it creates list.

With simple python operations, you can display an internal list using float. This will convert all string elements to float and make it the zero indexed element of your list.

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 to run

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]]

float, , 0.0

+1

Source: https://habr.com/ru/post/1524452/


All Articles