简体   繁体   中英

How to convert only integars of an array of strings to an array of floats in numpy?

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]

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

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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM