【问题标题】:How to create 2D array in python如何在python中创建二维数组
【发布时间】:2018-10-02 04:33:18
【问题描述】:

我正在尝试创建一个名为“words_in_texts”的函数来获得这样的结果

words_in_texts(['hello', 'bye', 'world'], 
               pd.Series(['hello', 'hello world hello'])

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

我认为这个函数的参数应该是一个包含所有单词和一个系列的列表。

def words_in_texts(words, texts):
'''
Args:
    words (list-like): words to find
    texts (Series): strings to search in

Returns:
    NumPy array of 0s and 1s with shape (n, p) where n is the
    number of texts and p is the number of words.
'''
indicator_array = texts.str.contains(words)

return indicator_array

我对如何创建二维数组结果感到困惑,谁能帮我解决这个问题?提前谢谢!

【问题讨论】:

    标签: arrays pandas series


    【解决方案1】:

    使用sklearn.feature_extraction.text.CountVectorizer:

    In [52]: from sklearn.feature_extraction.text import CountVectorizer
    
    In [53]: vect = CountVectorizer(vocabulary=['hello', 'bye', 'world'], binary=True)
    
    In [54]: X = vect.fit_transform(pd.Series(['hello', 'hello world hello']))
    

    结果为稀疏矩阵:

    In [55]: X
    Out[55]:
    <2x3 sparse matrix of type '<class 'numpy.int64'>'
            with 3 stored elements in Compressed Sparse Row format>
    

    您可以将其转换为密集矩阵:

    In [56]: X.A
    Out[56]:
    array([[1, 0, 0],
           [1, 0, 1]], dtype=int64)
    

    特征(列名):

    In [57]: vect.get_feature_names()
    Out[57]: ['hello', 'bye', 'world']
    

    【讨论】:

    • 哈哈,我的链接编辑和你的有冲突。很好的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 2011-12-23
    • 1970-01-01
    相关资源
    最近更新 更多