亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在Python中獲取兩個數據幀之間包含子字符串的字符串行數的最快方法

在Python中獲取兩個數據幀之間包含子字符串的字符串行數的最快方法

料青山看我應如是 2023-09-12 17:29:43
我有兩個數據框,一個有單詞,另一個有文本。我想獲取第一個數據框中包含該單詞的所有行的計數。字=ID   | Word------------1    | Introduction2    | database3    | country 4    | search文字 =ID   | Text------------1    | Introduction to python2    | sql is a database3    | Introduction to python in our country4    | search for a python teacher in our country我想要的最終輸出是ID   | Word  |  Count---------------------1    | Introduction  | 22    | database  | 13    | country  |  14    | search  |  2我在單詞 df 中有 200000 行,在文本中有 55000 行(每個文本的長度約為 2000 個單詞)df。使用以下代碼完成整個過程大約需要 76 小時'''def docCount(docdf, worddf):    final_dict = {}    for i in tqdm(worddf.itertuples()):        docdf["Count"] = docdf.Text.str.contains(i[2])        temp_dict = {i[2]: docdf.Count.sum()}        final_dict = dict(Counter(final_dict)+Counter(temp_dict))    return final_dict'''
查看完整描述

3 回答

?
SMILET

TA貢獻1796條經驗 獲得超4個贊

您可以嘗試這個示例來加快速度:


df1 = pd.DataFrame({'Word':['Introduction', 'database', 'country', 'search']})

df2 = pd.DataFrame({'Text':['Introduction to python', 'sql is a database', 'Introduction to python in our country', 'search for a python teacher in our country']})


tmp = pd.DataFrame(df2['Text'].str.split().explode()).set_index('Text').assign(c=1)

tmp = tmp.groupby(tmp.index)['c'].sum()

print( df1.merge(tmp, left_on='Word', right_on=tmp.index) )

印刷:


           Word  c

0  Introduction  2

1      database  1

2       country  2

3        search  1



查看完整回答
反對 回復 2023-09-12
?
當年話下

TA貢獻1890條經驗 獲得超9個贊

Series.str.splitSeries.explodefor 系列單詞一起使用:


s = df2['Text'].str.split().explode()

#oldier pandas versions

#s = df2['Text'].str.split(expand=True).stack()

然后僅按Series.isin和過濾匹配的值boolean indexing,按Series.value_counts和 最后一次使用進行計數DataFrame.join


df1 = df1.join(s[s.isin(df1['Word'])].value_counts().rename('Count'), on='Word')

print (df1)

? ? ? ? ? ?Word? Count

0? Introduction? ? ? 2

1? ? ? database? ? ? 1

2? ? ? ?country? ? ? 2

3? ? ? ? search? ? ? 1


查看完整回答
反對 回復 2023-09-12
?
慕勒3428872

TA貢獻1848條經驗 獲得超6個贊

這是簡單的解決方案

world_count = pd.DataFrame(

    {'words': Word['Word'].tolist(),

     'count': [Text['Text'].str.contains(w).sum() for w in words],

    }).rename_axis('ID')

輸出:


world_count.head()


'''

           words  count

ID                     

0   Introduction      2

1       database      1

2        country      2

3         search      1

'''

逐步解決方案:


# Convert column to list

words = Word['Word'].tolist()


# Get the count

count = [Text['Text'].str.contains(w).sum() for w in words]


world_count = pd.DataFrame(

    {'words': words,

     'count': count,

    }).rename_axis('ID')

提示:


我建議您轉換為小寫,這樣您就不會因為大/小寫而錯過任何計數


import re

import pandas as pd


world_count = pd.DataFrame(

    {'words': Word['Word'].str.lower().str.strip().tolist(),

     'count': [Text['Text'].str.contains(w,flags=re.IGNORECASE, regex=True).sum() for w in words],

    }).rename_axis('ID')


查看完整回答
反對 回復 2023-09-12
  • 3 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號