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?

yatu
  • 86,083
  • 12
  • 84
  • 139
Ribery
  • 23
  • 3

2 Answers2

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']
yatu
  • 86,083
  • 12
  • 84
  • 139
  • `float(i)` if OP *really* is looking for an *array of floats*, however the expected output in the question suggests otherwise. – r.ook Feb 20 '19 at 16:41
  • 2
    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` – mad_ Feb 20 '19 at 17:08
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"]