【问题标题】:How to convert a list of ndarray of strings into floats如何将字符串的ndarray列表转换为浮点数
【发布时间】:2021-10-05 08:13:37
【问题描述】:

如何将包含字符串对象的 ndarray 列表映射到特定的浮点数?例如,如果用户决定将 orange 映射到 1.0 并将 grapefruit 映射到 2.0 ?

myList = [np.array([['orange'], ['orange'], ['grapefruit']], dtype=object), np.array([['orange'], ['grapefruit'], ['orange']], dtype=object)] 

所以有人会:

convList = [np.array([['1.0'], ['1.0'], ['2.0']], dtype=float), np.array([['1.0'], ['2.0'], ['1.0']], dtype=float)]

我尝试实现这个功能:

def map_str_to_float(iterator):
    d = {}
    for ndarr in iterator:
        for string_ in ndarr:
            d[string_] = float(input('Enter your map for {}: '.format(string_)))
    return d

test = map_str_to_float(myList)
print(test)

但我收到以下错误:

d[string_] = float(input('Enter your map for {}: '.format(string_)))
TypeError: unhashable type: 'numpy.ndarray'

我相信这是因为string_ 的类型是一个numpy 数组而不是一个字符串...

【问题讨论】:

    标签: python string floating-point type-conversion numpy-ndarray


    【解决方案1】:

    使用该嵌套循环,您将要求用户输入 6 次(但您有 2 个值 grapefruitorange)。我建议您先获取唯一值,然后只要求唯一值:

    这样做:

    unique_values = np.unique(np.array(myList))
    

    现在作为一个数字的每个唯一值的用户:

    d = {}
    
    for unique_value in unique_values:
        d[unique_value] = float(input(f"give me a number for {unique_value} ")) 
    

    现在您的地图在变量 d 中。

    评论后更新

    然后您可以编写自己独特的方法。 请注意,只要它是 1D,下面的代码将获得所有唯一值,无论其长度如何。

    unique_values = []
    for each_ndarray in myList:
        for value in each_ndarray:
            if not value[0] in unique_values:
                unique_values.append(value[0])
    

    【讨论】:

    • 如果 myList 有不同大小的 numpy 条目,那么 np.array(myList) 会失败
    【解决方案2】:

    对于错误,调试时string_是一个数组['orange'],不能是字典的键

    至于如何将ndarray的字符串列表转换为浮点数 我们使用索引,获取字符串的索引,并使用这些索引以相同的顺序打印所需的新索引。 基本上np.array([1, 2])[0, 1, 0, 0] 将给出大小为 4 的新数组,其中条目按索引顺序排列。将应用相同的逻辑,这将跳过 python 中的字典映射。映射操作将通过 C 中的索引进行,因此应该很快。

    评论应该解释会发生什么

    import numpy as np
    
    dataSet = np.array(['kevin', 'greg', 'george', 'kevin'], dtype='U21')
    
    # Get all the unique strings, and their indices
    # Values of indices are based on uniques ordering
    uniques, indices = np.unique(dataSet, return_inverse=True)
    # >>> uniques
    # array(['george', 'greg', 'kevin'], dtype='<U21')
    # >>> indices
    # array([2, 1, 0, 2])
    # Originial array
    # >>> uniques[indices]
    # array(['kevin', 'greg', 'george', 'kevin'], dtype='<U21')
    
    new_indices = np.array([float(input()) for e in uniques])
    
    # Get new indices indexed using original positions of unique strings in numpy array
    print(new_indices[indices])
    
    # You can do the same for multi dimensional arrays
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 2011-11-25
      • 2021-09-23
      • 1970-01-01
      • 2017-09-26
      相关资源
      最近更新 更多