【问题标题】:Transform list of strings (indexes) to Numpy Array将字符串(索引)列表转换为 Numpy 数组
【发布时间】:2017-05-02 19:35:43
【问题描述】:

我有一个列表,其中每个值只显示一个,我还有另一个列表,其中包含所需的标记化 numpy 数组顺序。

例如:

sorted_values = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
a = ['a', 'c', 'g']
b = ['e']

我想将 a 和 b(高效)转换为 numpy 数组,如下所示:

at = [1,0,1,0,0,0,1]
bt = [0,0,0,0,1,0,0]

有什么有效的方法吗?

【问题讨论】:

    标签: python arrays pandas numpy


    【解决方案1】:

    你可以使用np.in1d:

    np.in1d(sorted_values, a).astype(int)
    #array([1, 0, 1, 0, 0, 0, 1])
    
    np.in1d(sorted_values, b).astype(int)
    #array([0, 0, 0, 0, 1, 0, 0])
    

    【讨论】:

      【解决方案2】:

      利用第一个数组已经排序的事实,我们可以使用np.searchsorted 来提高效率 -

      at = np.zeros(len(sorted_values), dtype=int)
      bt = at.copy()
      at[np.searchsorted(sorted_values, a)] = 1
      bt[np.searchsorted(sorted_values, b)] = 1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-24
        • 1970-01-01
        • 2019-10-31
        • 1970-01-01
        • 1970-01-01
        • 2013-05-05
        • 2016-03-10
        • 2021-04-26
        相关资源
        最近更新 更多