【问题标题】:Non-looping way in Numpy to convert a string of letters into a boolean array (corresponding to each letter of the string)Numpy中将一串字母转换为布尔数组的非循环方式(对应字符串的每个字母)
【发布时间】:2021-08-02 10:50:54
【问题描述】:

我有一个字符串数组,我想将这些字符串分别视为对应于字母表 (A-Z) 的布尔数组。

我的目标是以矢量化方式执行此操作并避免任何循环。

例如

Input:
A = np.array(['A'])
B = np.array(['AB'])
C = np.array(['AZ'])
D = np.array(['AZ','BAZ'])


Output:
A = np.array([1,0,0,0,...0]) 
B = np.array([1,1,0,0,...0])
C = np.array([1,0,0,0,...1])
D = np.array([[1,0,0,0,...1], [1,1,0,0,...1]])

【问题讨论】:

    标签: python arrays pandas string numpy


    【解决方案1】:

    mapMultiLabelBinarizer.transform

    我们可以在A-Z的大写字母上fitMultiLabelBinarizer,然后使用MultiLabelBinarizer的变换方法变换数组A、B、C和D

    import string
    from sklearn.preprocessing import MultiLabelBinarizer
    
    mlb = MultiLabelBinarizer().fit([*string.ascii_uppercase])
    A, B, C, D = map(mlb.transform, (A, B, C, D))
    

    >>> A
    array([[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0]])
    
    >>> B
    array([[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-17
      • 2016-02-07
      • 2019-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      相关资源
      最近更新 更多