-1

I have the following NumPy array of strings

array(['cwp+17', 'cn95', 'awd+12', ..., 'dgb+19', 'mbc+19', 'acd+19']

I have sliced this array as follows to get the number part

RA = [x[-2:] for x in RA]
RA = np.asarray(RA)

and now it looks like this

array(['17', '95', '12', ..., '19', '19', '19'], dtype='<U2')

Now, I would like to convert this array of string to NumPy float array. I have tried the methods described in this post and few other places, but I am receiving the error in the title. Why these methods do not work in my string arrays and how can I convert it? Thanks.

Sara Krauss
  • 388
  • 3
  • 17
  • 2
    One of your strings ends with `7a`, which isn't a valid number. – Barmar Jun 08 '20 at 22:09
  • The `...` in your example hides the problem. – John Coleman Jun 08 '20 at 22:11
  • 1
    It would be relatively easy to write a function which takes 2-chacter strings which begin with a digit and whose second digit is either a digit or some other character and extract a float out of it, but the fact that you are getting this error at all suggests that you don't fully understand the structure of the strings. Maybe it isn't safe to always just take the last two characters. Don't just put a bandaid on the problem, make sure you understand its source. A more principled approach might be to use a regular expression. – John Coleman Jun 08 '20 at 22:17

1 Answers1

2
RA = np.array(['cwp+17', 'cn95', 'awd+12', 'aw+7a'])
RA = [re.findall(r'\d+|$', x)[0] for x in RA]
RA = np.asarray(RA).astype(np.float)
print(RA)

out:
[17. 95. 12.  7.]