python - 如何将 ndarray 字符串列表转换为 float

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

如何将包含字符串对象的 ndarray 列表映射到特定的 float ?例如,如果用户决定将 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 数组而不是字符串......

最佳答案

对于错误,调试时 string_ is an array ['orange'], cant be key ofdictionary

至于如何将字符串的ndarray列表转换为 float 我们使用索引,获取字符串的索引,并使用这些索引以相同的顺序打印所需的新索引。 基本上 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

关于python - 如何将 ndarray 字符串列表转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68579845/

相关文章:

python - 如何在 Gtk 对话框中显示视频?

c++ - pyQT slot decorator 什么是 C++ 等价物

python - 使用 Python click 命令调用带有可变参数的类方法

javascript - 如何将复杂的 JavaScript 对象转换为字符串并返回

c# - C#中如何判断一个对象是否可以转换为有意义的字符串

php - preg_replace 不接受 unicode

python - 如何在填充单元格前后填充空白?

c++ - 在任何情况下都可以使用整数或 float ?

c++ - 这种使用 SSE 处理数组尾部的方法是否矫枉过正?

python - Python doctest 中限制浮点精度比较的最佳方法