代码之家  ›  专栏  ›  技术社区  ›  Christopher

numpy数组:条件编码

  •  1
  • Christopher  · 技术社区  · 7 年前

    我有以下numpy数组:

    array([1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 2, 0, 1, 1, 2, 3, 3, 3, 3, 1, 1, 1, 1,
           1, 3, 1, 1, 3, 0, 1, 3, 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 0, 1, 2, 0, 2,
           2, 2, 1, 2, 2, 0, 2, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 3, 0, 2, 1, 1,
           1, 1, 3, 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 0, 2, 3,
           2, 1, 1, 1, 1, 3, 1, 0])
    

    问题:在给定条件下,我如何创建另一个对数据进行编码的数组:如果值=3或2,则为“1”,否则为“0”。

    我尝试过:

    from sklearn.preprocessing import label_binarize
    label_binarize(doc_topics, classes=[3,2])[:15]
    
    array([[0, 0],
           [0, 0],
           [0, 0],
           [1, 0],
           [0, 0],
           [0, 0],
           [0, 0],
           [0, 0],
           [0, 0],
           [0, 0],
           [0, 1],
           [0, 0],
           [0, 0],
           [0, 0],
           [0, 1]])
    

    然而,这似乎返回一个二维数组。

    1 回复  |  直到 7 年前
        1
  •  1
  •   EdChum Arthur G    7 年前

    np.where 1 0

    In[18]:
    a = np.where((a==3) | (a == 2),1,0)
    a
    
    Out[18]: 
    array([0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0,
           0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1,
           0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0,
           1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0,
           0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0])
    

    | or ()

    In[68]:
    binarizer = preprocessing.Binarizer(threshold=1)
    binarizer.transform(a.reshape(1,-1))
    
    Out[68]: 
    array([[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0,
            0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1,
            0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0,
            1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0,
            0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0]])
    

    2 3 numpy