【问题标题】:How to count string similarity by using pandas dataframe more faster如何更快地使用熊猫数据框计算字符串相似度
【发布时间】:2018-05-25 18:42:47
【问题描述】:

我有两只熊猫dataframes,我想计算dataframes 的字符串相似度。这是我的代码,但我遇到的一个大问题是我的数据出价太高,而且我的代码花费了太多时间(可能需要 7 天)。有什么方法可以让我的代码更快?

import pandas as pd
import re
import difflib

df_post=pd.read_csv('ptt_run.csv',encoding='utf8',header=0)
df_post=df_post.fillna('null')
df_yahoo=pd.read_csv('yahoo_movie_20180519_test.csv',encoding='utf8',header=0)
df_yahoo=df_yahoo.fillna('null')

for i in range(0,len(df_yahoo)):
    df_post[df_yahoo['yahoo_movie_id'][i]]=0

    for j in range(0,len(df_post)):
        df_post.loc[j, df_yahoo['yahoo_movie_id'][i]]=difflib.SequenceMatcher(None, df_yahoo['yahoo_ch_nosign'][i], df_post['title_nosign'][j]).ratio()

df_post.to_csv('df_score_test.csv', encoding='utf8',index=False)

我的len(df_yahoo)=6000len(df_post)=130000
我想知道 df_yahoo['yahoo_ch_nosign'][0] 与 df_post['title_nosign'][0~13000] 与 df_yahoo['yahoo_ch_nosign'][6000] 与 df_post['title_nosign'][0~13000] 的相似性 这样做for循环花费了太多时间,但我不知道如何改进我的问题。

【问题讨论】:

    标签: python python-3.x pandas dataframe similarity


    【解决方案1】:

    基本上像你的情况那样进行手动循环是最慢的方法,它没有利用内置的 pandas/numpy 方法。

    这篇文章很好地澄清了这个问题:https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      • 2013-06-24
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多