如何仅将字符串数组的整数转换为numpy中的浮点数组?

时间:2019-02-20 16:34:34

标签: python arrays list numpy

如何转换

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

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

在NumPy中?

与这个问题How to convert an array of strings to an array of floats in numpy?类似,除了也有单词之外,还有办法吗?

2 个答案:

答案 0 :(得分:3)

您可以使用列表推导来检查列表中的元素是否为数字,并相应地返回字符串或int

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

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

输出

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

答案 1 :(得分:0)

假设您的列表可以同时包含int和float。 (您的引用包含浮点数,示例包含列表),您可以使用如下列表理解:

mtlView.device = device

它将返回以下数组:

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]
相关问题