为了账号安全,请及时绑定邮箱和手机立即绑定

计算 pandas 列中的唯一单词

计算 pandas 列中的唯一单词

慕少森 2023-12-12 20:10:52
我对以下数据(来自 pandas 数据框)遇到一些困难:Text0   Selected moments from Fifa game t...1   What I learned is that I am ...3   Bill Gates kept telling us it was comi...5   scenario created a month before the...... ...1899    Events for May 19 – October 7 - October CTOvision.com1900    Office of Event Services and Campus Center Ope...1901    How the CARES Act May Affect Gift Planning in ...1902    City of Rohnert Park: Home1903    iHeartMedia, Inc.我需要提取每行的唯一单词数(删除标点符号后)。因此,例如:Unique0   61   63   85   6... ...1899    81900    81901    9 1902    51903    2我尝试按如下方式进行:df["Unique"]=df['Text'].str.lower()df["Unique"]==Counter(word_tokenize('\n'.join( file["Unique"])))但我没有得到任何计数,只有一个单词列表(没有它们在该行中的频率)。你能告诉我出了什么问题吗?
查看完整描述

3 回答

?
饮歌长啸

TA贡献1951条经验 获得超3个赞

如果不需要计数,请先删除所有标点符号。杠杆套。str.split.map(set)会给你一套。计算后面集合中的元素。集合不采用多个唯一元素。

链式

df['Text'].str.replace(r'[^\w\s]+', '').str.split().map(set).str.len()

逐步

df[Text]=df['Text'].str.replace(r'[^\w\s]+', '')
df['New Text']=df.Text.str.split().map(set).str.len()


查看完整回答
反对 回复 2023-12-12
?
GCT1015

TA贡献1827条经验 获得超4个赞

所以,我只是根据评论更新这一点。该解决方案还考虑了标点符号。

df['Unique'] =  df['Text'].apply(lambda x: x.translate(str.maketrans('', '', string.punctuation)).strip()).str.split(' ').apply(len)


查看完整回答
反对 回复 2023-12-12
?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

尝试这个


from collections import Counter


dict = {'A': {0:'John', 1:'Bob'},

        'Desc': {0:'Bill ,Gates Started Microsoft at 18 Bill', 1:'Bill Gates, Again .Bill Gates  and Larry Ellison'}}


df = pd.DataFrame(dict)

df['Desc']=df['Desc'].str.replace(r'[^\w\s]+', '')

print(df.loc[:,"Desc"])

 

print(Counter(" ".join(df.loc[0:0,"Desc"]).split(" ")).items())

print(len(Counter(" ".join(df.loc[0:0,"Desc"]).split(" ")).items()))


查看完整回答
反对 回复 2023-12-12
  • 3 回答
  • 0 关注
  • 65 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信