【问题标题】:Creating a list of strings defined by similar items in a `numpy.array`在“numpy.array”中创建由类似项目定义的字符串列表
【发布时间】:2020-11-29 23:44:21
【问题描述】:

鉴于:

  • 字符串列表:
colors = ['red', 'blue', 'green', 'grey', 'black', 'yellow', 'brown', 'orange', 'magenta', 'cyan', 'teal', 'turquise']
  • anumpy.arraya.shape[0] len(colors),其中包含一些数字(重复)值。

要求:

生成l 的列表str 对象,这些对象将匹配a 中的元素。 IE。对于a 中的每个元素,l 中都会有相同的str 对象,如Example 1 所示。

示例 1:

给定:

import numpy as np


colors = ['red', 'blue', 'green', 'grey', 'black', 'yellow', 'brown', 'orange', 'magenta', 'cyan', 'teal', 'turquise']

a = np.array([0, 1, 5, 7, 1, 5, 7, 7, 0, 0])

所需的输出应该是:

Out: ['red', 'blue', 'green', 'grey', 'blue', 'green', 'grey', 'grey', 'red', 'red']

我的解决方案:

我可以想到两种方法,如Code 1Code 2 所示。

代码 1:

import numpy as np

colors = ['red', 'blue', 'green', 'grey', 'black', 'yellow', 'brown', 'orange', 'magenta', 'cyan', 'teal', 'turquise']
a = np.array([0, 1, 5, 7, 1, 5, 7, 7, 0, 0])

num_2_color_dict = {}
for num in np.unique(a):
    num_2_color_dict[num] = colors[np.min(np.where(a==num))]
    
color_by_num = []
for num in a:
    color_by_num.append(num_2_color_dict[num])
color_by_num
Out: ['red', 'blue', 'green', 'grey', 'blue', 'green', 'grey', 'grey', 'red', 'red']

代码 2:

import numpy as np

colors = ['red', 'blue', 'green', 'grey', 'black', 'yellow', 'brown', 'orange', 'magenta', 'cyan', 'teal', 'turquise']
a = np.array([0, 1, 5, 7, 1, 5, 7, 7, 0, 0])

colors_by_num = [colors[np.min(np.where(np.unique(a)==num))] for num in a]
colors_by_num

问题:

我希望能够在不使用循环的情况下获得相同的结果,最好使用一些 numpy 数组操作技术,这将缩短代码。

提前致谢。

【问题讨论】:

    标签: python python-3.x numpy


    【解决方案1】:

    正如 Josef 在他的 answer 中所述,numpy.unique 可以选择返回整数编码,这正是您想要的。因此,以下代码应该可以帮助您:

    np.take(colors, np.unique(a,return_inverse=True)[1])
    

    通过设置return_inverse=True,您可以获得整数编码,作为第二个返回参数。 Numpy.take() 为您提供索引项目。

    【讨论】:

      【解决方案2】:
      colors = np.array(['red', 'blue', 'green', 'grey', 'black', 'yellow', 'brown', 'orange', 'magenta', 'cyan', 'teal', 'turquise'])
      a      = np.array([0, 1, 5, 7, 1, 5, 7, 7, 0, 0])
      
      _, i = np.where(a[:, None] == np.unique(a))
      
      colors[i]
      
      
      >>> array(['red', 'blue', 'green', 'grey', 'blue', 'green', 'grey', 'grey', 'red', 'red'])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-13
        • 1970-01-01
        • 1970-01-01
        • 2019-09-29
        • 1970-01-01
        相关资源
        最近更新 更多