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:
a = a.tolist()
Result:
[[-0.99, 0.0, 0.56, 0.56, -2.02, -0.96]]
Answer from abudis on Stack Overflowimport 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:
a = a.tolist()
Result:
[[-0.99, 0.0, 0.56, 0.56, -2.02, -0.96]]
That is a pure python solution and it produces a 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.
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
python - Convert Numpy array with 'n' and 'y' into integer array of 0 and 1 - Data Science Stack Exchange
python - Convert string array to numpy array - Stack Overflow
python 3.x - How to convert elements type in numpy array from string to int - Stack Overflow
python convert string to integer array - Stack Overflow
If you have x = np.matrix, where each element is '1.0' (as str) and you want to convert it to int or float:
x = x.astype(np.float)
import numpy as np
nums_str = ['1','23','345']
nums_str_np = np.asarray(nums_str)
nums_int_np = nums_str_np.astype('int')
nums_int_np - is now np array of integers.
It is quite trivial
(X=='y').astype(int)
Should do the trick. It simply converts your array to True or False according to your requirements and then astype will impose the required datatype. By default int will give you 1 for True and 0 for False.
You could use the following code:
X[X=='y'] = 1
X[X=='n'] = 0
This replaces the indexes of 'y' with 1 and of 'n' with 0.
Generally the X=='y' returns a Boolean array which contains True where the 'y' and False everywhere else and so on.
Numpy as can handle it much easier than all the answers:
s = '[ 0. 0. 1.]'
np.fromstring(s[1:-1],sep=' ').astype(int)
IN:
import numpy as np
s = '[ 0. 0. 1.]'
out = np.array([int(i.replace('.','')) for i in s[s.find('[')+1:s.find(']')].split()])
print(type(out))
OUT:
<class 'numpy.ndarray'>