1

I am trying to convert string to float type by the following

X = arr[:,:-1].astype(np.float32)

However, error as below is rising

ValueError: could not convert string to float: '"53"'

I know this means I have some elements with extra quote in the array. My problem is how should I solve this. How can I convert element '"53"' into 53 inside the array?

UPDATE 1: Here is an example to reproduce

import numpy as np
a = np.array([['12','13'],['"53"','44']])
a = a.astype(np.float32)
1
  • 1
    It would be nice if you could provide a reproducible example. Commented Nov 14, 2018 at 5:17

2 Answers 2

4

Try stripping the double quotes from the array, then casting to float.

Like so:

arr = np.char.strip(arr, '"')
X = arr[:,:-1].astype(np.float32)
Sign up to request clarification or add additional context in comments.

Comments

1

You could also use numpy.char.replace() to perform element-wise string replace on an array of strings.

Signature: np.char.replace(a, old, new, count=None)

Docstring: For each element in a, return a copy of the string with all occurrences of substring old replaced by new. Calls str.replace element-wise.


import numpy as np
a = np.array([["12","13"],['"53"',"44"]])

b = np.char.replace(a, '"', '')
c = b.astype(np.float32)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.