1

How to convert

["5", "3","Code", "9","Pin"]

to

[5, 3,"Code", 9,"Pin"]

in NumPy?

It is similar to this question How to convert an array of strings to an array of floats in numpy? with the exception of having words as well is there a way?

1
  • 1
    It would seem your question is answered in the comments of the top answer of the question you've linked. Commented Feb 20, 2019 at 16:37

2 Answers 2

3

You can use a list comprehension to check if the elements in the list are numeric or not, and return a string or an int accordingly:

l = ["5", "3","Code", "9","Pin"]

[int(i) if i.isnumeric() else i for i in l]

Output

[5, 3, 'Code', 9, 'Pin']
Sign up to request clarification or add additional context in comments.

2 Comments

float(i) if OP really is looking for an array of floats, however the expected output in the question suggests otherwise.
No, you cannot convert into floats directly because isnumeric() will not work as excepted for floats wrapped in string. For example '5.4'.isnumeric() will return False but will work for int
0

Assuming that your list can contain both int and float. (Your reference contains float, and your example contains list), you can use a list comprehension like below :

l = ["5", "3","Code", "9", "4.5", "Pin"]

def isfloat(value):
    try:
        float(value)
        return True
    except ValueError:
        return False

l = [int(elem) if elem.isnumeric() else (float(elem) if isfloat(elem) else elem) for elem in l]

It would return the following array :

[5, 3, "Code", 9, 4.5, "Pin"]

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.