【问题标题】:How to convert a numpy array of strings to a numpy array of sets to use MultiLabelBinarizer?如何将 numpy 字符串数组转换为 numpy 集合数组以使用 MultiLabelBinarizer?
【发布时间】:2018-08-15 16:08:43
【问题描述】:

我有一个这样的 numpy 数组:

l1 = (['United States', 'England', 'South Africa']). 

有时它可能有 >1 个值:

l1 = ([['United States','South Korea'], 'England', 'South Africa'])

我想使用 MultiLabelBinarizer 对这些值进行编码。根据 scikit-learn 文档中 fit_transform 的文档。参数应该是

y : iterable of iterables 每个样本的一组标签(任何可排序和可散列的对象)。如果设置了 classes 参数,y 将不会被迭代。

如何将这个由列表和单个字符串组成的 numpy 数组转换为集合?

我试过这个:

value = [set(v) for v in l1]
list_2sets = np.asarray(value)

但它似乎无法正常工作。

问题是我没有考虑(所有国家)的价值观。如果我有这个,我尝试了以下方法:

 mlb.fit_transform(headings.split(', ') for headings in l1)

作为标题考虑的所有值的列表:

['England','Spain', ...]

但到目前为止我还没有这些值,所以我想尝试在没有'headings'的情况下应用 MLB

【问题讨论】:

    标签: python arrays numpy encoding scikit-learn


    【解决方案1】:

    尝试如下预处理字符串数组:

    In [50]: l1 = [[x] if isinstance(x, (str)) else x for x in l1]
    
    In [51]: l1
    Out[51]: [['United States', 'South Korea'], ['England'], ['South Africa']]
    

    对于 Python 2.x:

    In [50]: l1 = [[x] if isinstance(x, (str, unicode)) else x for x in l1]
    
    In [51]: l1
    Out[51]: [['United States', 'South Korea'], ['England'], ['South Africa']]
    

    【讨论】:

      猜你喜欢
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 2021-04-26
      • 2015-03-28
      • 2018-09-19
      • 1970-01-01
      • 2016-03-10
      相关资源
      最近更新 更多