应用dataframe.apply()时查看进度的方法?

2024-10-03 19:25:45 发布

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

我正在应用一个将文本转换为tf IDF的函数,但它似乎花费了太多的时间来构建它。 我在想是否有可能看到使用.apply()函数的进展

people['word_count'] = people['text'].apply(get_ifidf_for_words)
people

这是我申请的职位

from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np

people = pd.read_csv('/content/drive/My Drive/people_wiki1.csv')

tfidf = TfidfVectorizer()
tfidf.fit(list(people['text'].values.tolist()))
feature_names = tfidf.get_feature_names()

def get_ifidf_for_words(text):
    tfidf_matrix= tfidf.transform([text]).todense()
    feature_index = tfidf_matrix[0,:].nonzero()[1]
    tfidf_scores =[tfidf_matrix[0, x] for x in feature_index]
    return tfidf_scores

Tags: csv函数textimportforgetnamespeople
1条回答
网友
1楼 · 发布于 2024-10-03 19:25:45

我曾经做过一次这样的工作:

将函数重新定义为

def get_ifidf_for_words(row):
    # Progress measurement
    if not row.iat[1] % 5:
        print(f'Progress: {row.iat[1]}%')
    
    # Actual function
    text = row.iat[0]
    tfidf_matrix= tfidf.transform([text]).todense()
    feature_index = tfidf_matrix[0,:].nonzero()[1]
    tfidf_scores =[tfidf_matrix[0, x] for x in feature_index]
    return tfidf_scores

然后按以下方式使用apply

people['word_count'] = pd.DataFrame(
                            {'text': people['text'].values,
                             'prog': [int(100 * i / people.shape[0])
                                      for i in range(1, people.shape[0]+1)]}
                       ).apply(get_ifidf_for_words, axis='columns')

在控制台上获取进度消息的步骤

Progress: 5%
Progress: 10%
Progress: 15%
...

逻辑:向people['text']添加一个进度列,赋予apply的函数使用该列打印进度

(我不是说它漂亮。)

相关问题 更多 >