【问题标题】:How to iterate a function with strings over a pandas dataframe如何在 Pandas 数据帧上使用字符串迭代函数
【发布时间】:2021-04-14 11:49:01
【问题描述】:

我想获得我的数据框和基础之间的 Jaccard 相似度。问题是我需要 500 多行,我要么收到错误消息:"too many values to unpack", 'Series' object has no attribute 'iterrows'或函数将基数与整个数据帧进行比较。

备选方案A:

sentences = pd.Series(df.sentence)
sentences = sentences.str.replace('[^A-z ]','').str.replace(' +',' ').str.strip()
splitwords = [ nltk.word_tokenize( str(sentence) ) for sentence in sentences ]
print(splitwords)
sentence = df.sentence
def Jaccard_Similarity(base, sentence):
    for i, row in sentence.iterrows():
        a = set(word for word in base)
        b = set(word for word in df.sentence())
        c = a.intersection(b)
        return(float(len(c)) / (len(a) + len(b) - len(c)), a, b)
Jaccard_Similarity(base, sentence)

备选方案 B:

df = df.apply(lambda row: nltk.word_tokenize(row['sentence']), axis=1)
print(df)

def Jaccard_Similarity(bas, df):
    for row in df.iterrows(df):
        a = set(word for word in base)
        b = set(word for word in df)
        c = a.intersection(b)
        return(float(len(c)) / (len(a) + len(b) - len(c)), a, b)
Jaccard_Similarity(base, df)

数据:

base = ['Tom', 'eats', 'apple']    
df = (["Tom eats an apple"],
          ["Tom eats a pineapple"],
          ["Eva eats an apple"],
          ["Eva eats a pineapple"],
         columns = 'sentence')  

编辑:

   base = set(base.lower().split()) 
   df = set(df.lower().split())

def Jaccard_Similarity(base, df): 
    intersection = base.intersection(df)
    union = base.union(df)
    return float(len(intersection)) / len(union)

【问题讨论】:

  • 仅供参考:如果您打算使用 '[^A-z ]' 删除除 ASCII 字母和空格以外的所有字符,您应该知道 [A-z] matches more than just letters。你需要[^a-zA-Z ]
  • 是的,理想情况下,它也会在开头删除一些对成功分类没有帮助的数字。

标签: python pandas tokenize


【解决方案1】:

试试这个 - 我稍后会添加解释需要一些工作来做。

import nltk
from nltk.corpus import stopwords # to remove stopwords

base = ['Tom', 'eats', 'apple']
base = [item.lower() for item in base]
stop_words = set(stopwords.words('english')) 
list1 = [["Tom eats an apple"],
          ["Tom eats a pineapple"],
          ["Eva eats an apple"],
          ["Eva eats a pineapple"]]
df = pd.DataFrame(list1, columns= ['sentence'])
df = df.sentence.apply(nltk.word_tokenize)
df = df.apply(
    lambda x: [item.lower() for item in x if item.lower() not in stop_words]
)
b = df.apply(set)
a = set(base)
c =  b.apply(lambda x : a.intersection(x))
len_a_b = b.apply(lambda x : len(x) +  len(a))
len_c  = c.apply(lambda x : len(x))
dict1 = {'length' : len_c / (len_a_b - len_c) , 'b' : b , 'c' : c}
import numpy as np
df = pd.DataFrame(dict1)
df['a'] = np.NAN
df['a'] = df.a.apply(lambda x: a)
print(df)

输出 -

   length                       b                   c                   a
0     1.0      {apple, eats, tom}  {apple, eats, tom}  {apple, eats, tom}
1     0.5  {eats, tom, pineapple}         {eats, tom}  {apple, eats, tom}
2     0.5      {apple, eats, eva}       {apple, eats}  {apple, eats, tom}
3     0.2  {eats, pineapple, eva}              {eats}  {apple, eats, tom}

【讨论】:

  • 是的,这给了我更好的结果。如何排除停用词和 lower()?
  • 使用df = df.str.replace('[^A-z ]','').str.replace(' +',' ').str.strip() 给我:AttributeError: 'DataFrame' object has no attribute 'str'
  • 使用 lower() 给了我这个:**AttributeError: 'Series' object has no attribute 'lower' ** 即使它不是一个系列,是吗?
  • 使用列表推导转换为小写。
  • 并从 ntlk.corpus 导入停用词以删除停用词
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
  • 2015-04-23
  • 1970-01-01
  • 2019-04-23
  • 2018-01-19
  • 2020-05-01
  • 2022-01-04
相关资源
最近更新 更多