【问题标题】:Calculate IDF (Inverse Document Frequency) on a pandas dataframe在 pandas 数据帧上计算 IDF(逆文档频率)
【发布时间】:2017-06-13 13:18:56
【问题描述】:

我有一个三列的数据框 df,如下所示:

DocumentID    Words             Region
1             ['A','B','C']     ['Canada']
2             ['A','X','D']     ['India', 'USA', 'Canada']
3             ['B','C','X']     ['Canada']

我想为“单词”列中的每个单词计算 IDF,即我想生成一个输出,其中每个单词(如 'A'、'B'、'C' 等)都有相应的 IDF 值。

【问题讨论】:

  • 那里有几个记录良好、维护良好且使用过的 NLP 库。您可能已经安装了几个。老实说,为什么你使用这样的DataFrame 对我来说毫无意义。 DataFrames 的列表几乎总是表明您以错误的方式处理此问题。

标签: python pandas dataframe tf-idf


【解决方案1】:

这是一个稍微不太具体的版本。假设您想要 IDF 的标准 1/df 定义,您可以遍历 Words 列计数中的每个“文档”:

from collections import defaultdict

# Assuming the Words column is represented as you presented it:
words = [['A','B','C'],
         ['A','X','D'],
         ['B','C','X']]

# to store intermediate counts:
idf = defaultdict(float)
for doc in words:
    for w in doc:
        idf[w] += 1

# Compute IDF as 1/df :
idf   = {k:(1/v) for (k,v) in idf.items()} #<- {'A': 0.5, 'B': 0.5,'C': 0.5, 'D': 1.0, 'X': 0.5}
vocab = idf.keys() # Note that the vocab is also accessible now.

【讨论】:

    【解决方案2】:
    list_words = []
    list_regions = []
    
    for words in df['Words']:
    
        for word in words:
    
            list_words.append(word)
    
    for regions in df['Region']:
    
        for region in regions:
    
            list_regions.append(region)
    
    IDF_words = pd.DataFrame([], columns=['words','IDF'])
    IDF_regions = pd.DataFrame([], columns=['regions','IDF'])
    
    IDF_words['words'] = sorted(set(list_words))
    IDF_regions['regions'] = sorted(set(list_regions))
    
    IDF_words['IDF'] = IDF_words['words'].map(lambda x: list_words.count(x)/float(len(list_words)))
    IDF_regions['IDF'] = IDF_regions['regions'].map(lambda x: list_regions.count(x)/float(len(list_regions)))
    

    希望对兄弟有帮助!
    如果确实如此,请投票/标记已回答:)
    和平

    【讨论】:

    • 也许对 OP:地区与 idf[w] 有什么关系吗?
    • @epattaro TypeError: unhashable type: 'list'
    • 它在这里完美运行。你有没有改变任何可能导致这种情况的东西?重要的是要注意 list.append(...) 之前不要相等。
    猜你喜欢
    • 2016-01-23
    • 2023-03-08
    • 2015-01-19
    • 2014-05-18
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多