返回pandas单元格中每个单词的列表以及该单词在整个列中的总数

2024-10-05 12:21:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas数据框,df,如下所示:

             column1
0   apple is a fruit
1        fruit sucks
2  apple tasty fruit
3   fruits what else
4      yup apple map
5   fire in the hole
6       that is true

我想生成一个column2,它是行中每个单词的列表以及整个列中每个单词的总数。所以输出应该是这样的。。。。在

^{pr2}$

我尝试使用sklearn,但未能达到上述目的。需要帮助。在

from sklearn.feature_extraction.text import CountVectorizer
v = CountVectorizer()
x = v.fit_transform(df['text'])

Tags: 数据textapplepandasdfissklearn单词
2条回答

以下是一种给出您想要的结果的方法,尽管它完全避免了sklearn

def counts(data, column):
    full_list = []
    datr = data[column].tolist()
    total_words = " ".join(datr).split(' ')
    # per rows
    for i in range(len(datr)):
        #first per row get the words
        word_list = re.sub("[^\w]", " ",  datr[i]).split()
        #cycle per word
        total_row = []
        for word in word_list:
            count = []
            count = total_words.count(word)
            val = (word, count)
            total_row.append(val)
        full_list.append(total_row)
    return full_list

df['column2'] = counts(df,'column1')
df
         column1                                    column2
0   apple is a fruit  [(apple, 3), (is, 2), (a, 1), (fruit, 3)]
1        fruit sucks                   [(fruit, 3), (sucks, 1)]
2  apple tasty fruit       [(apple, 3), (tasty, 1), (fruit, 3)]
3   fruits what else        [(fruits, 1), (what, 1), (else, 1)]
4      yup apple map           [(yup, 1), (apple, 3), (map, 1)]
5   fire in the hole  [(fire, 1), (in, 1), (the, 1), (hole, 1)]
6       that is true            [(that, 1), (is, 2), (true, 1)]

我不知道您是否可以使用scikit-learn来实现这一点,但是您可以编写一个函数,然后使用apply()将其应用于您的DataFrame或{}。在

以下是您可以如何进行的示例:

test = pd.DataFrame(['apple is a fruit', 'fruit sucks', 'apple tasty fruit'], columns = ['A'])

def a_function(row):
    splitted_row = str(row.values[0]).split()
    word_occurences = []
    for word in splitted_row:
        column_occurences = test.A.str.count(word).sum()
        word_occurences.append((word, column_occurences))
    return word_occurences

test.apply(a_function, axis = 1)

# Output
0    [(apple, 2), (is, 1), (a, 4), (fruit, 3)]
1                     [(fruit, 3), (sucks, 1)]
2         [(apple, 2), (tasty, 1), (fruit, 3)]
dtype: object

如您所见,主要问题是test.A.str.count(word)将计算word的所有出现次数,无论分配给word的模式在字符串内。这就是为什么"a"显示为发生4次。这应该很容易用一些正则表达式来解决(我不太擅长)。在

或者,如果您愿意丢失一些单词,可以在上面的函数中使用此解决方法:

^{pr2}$

相关问题 更多 >

    热门问题