【问题标题】:Assigning labels for different portions of the list为列表的不同部分分配标签
【发布时间】:2018-02-02 06:34:02
【问题描述】:

我有以下清单:

a = numpy.array([1,2,3,4,5,6])

我需要简单地将值 1,2,3 一起分配标签 04,5,6 标签 1

我首先想到的是numpy.concatenate,但不知道如何在我的情况下使用它。

有什么想法吗?

谢谢。

【问题讨论】:

  • 你期待这样的字典:{0:[1,2,3],1:[4,5,6]} 吗?

标签: python list numpy concatenation


【解决方案1】:

您可以先将 numpy 数组转换为列表,然后收集索引和子元素,然后将它们添加到字典中:

>>> import numpy as np
>>> a = np.array([1,2,3,4,5,6]).to_list()
>>> a
[1, 2, 3, 4, 5, 6]
>>> ind = [0, 1]
>>> sublists = [a[i:i+3] for i in range(0, len(a), 3)]
>>> sublists
[[1, 2, 3], [4, 5, 6]]
>>> d = dict(zip(ind, sublists))
>>> d
{0: [1, 2, 3], 1: [4, 5, 6]}
>>> d[0]
[1, 2, 3]
>>> d[1]
[4, 5, 6]

【讨论】:

    【解决方案2】:

    听起来您正在寻找这样的东西:

    In [30]: a = np.array([1,2,3,4,5,6])
    
    In [31]: labels = np.empty(len(a))
    
    In [32]: labels[np.in1d(a, [1,2,3])] = 0
    
    In [33]: labels[np.in1d(a, [4,5,6])] = 1
    
    In [34]: result = np.vstack((a, labels)).T
    
    In [35]: result
    Out[35]: 
    array([[ 1.,  0.],
           [ 2.,  0.],
           [ 3.,  0.],
           [ 4.,  1.],
           [ 5.,  1.],
           [ 6.,  1.]])
    

    【讨论】:

      猜你喜欢
      • 2016-03-19
      • 1970-01-01
      • 2022-01-24
      • 2022-01-04
      • 2018-10-03
      • 1970-01-01
      • 2012-03-08
      • 2019-02-13
      • 1970-01-01
      相关资源
      最近更新 更多