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?
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?
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']
float(i) if OP really is looking for an array of floats, however the expected output in the question suggests otherwise.isnumeric() will not work as excepted for floats wrapped in string. For example '5.4'.isnumeric() will return False but will work for intAssuming 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"]