【问题标题】:Is there any way to run the below code faster?有什么方法可以更快地运行下面的代码?
【发布时间】:2021-09-10 11:40:53
【问题描述】:

我为大约 20k 数据运行了以下代码。虽然代码很好,我能够得到输出,但运行速度很慢。获得输出花了将近 45 分钟。有人可以提供适当的解决方案吗?

代码:

import numpy as np
import pandas as pd
import re
def demoji(text): 

    emoji_pattern = re.compile("[" 

                               u"\U0001F600-\U0001F64F"  # emoticons 
                               u"\U0001F300-\U0001F5FF"  # symbols & pictographs 
                               u"\U0001F680-\U0001F6FF"  # transport & map symbols 
                               u"\U0001F1E0-\U0001F1FF"  # flags (iOS) 
                               u"\U00002500-\U00002BEF"  # chinese char 
                               u"\U00002702-\U000027B0" 
                               u"\U00002702-\U000027B0" 
                               u"\U000024C2-\U0001F251" 
                               u"\U0001f926-\U0001f937" 
                               u"\U00010000-\U0010ffff" 
                               u"\u2640-\u2642" 
                               u"\u2600-\u2B55" 
                               u"\u200d" 
                               u"\u23cf" 
                               u"\u23e9" 
                               u"\u231a" 
                               u"\ufe0f"  # dingbats 
                               u"\u3030" 
                               "]+", flags=re.UNICODE) 

    return(emoji_pattern.sub(r'', text)) 

df = pd.read_csv("data.csv")
print(df['Body'])
tweets=df.replace(to_replace=[r"\\t|\\n|\\r", "\t|/n|/r|w/|\n|w/|Quote::"], value=["",""], regex=True)
tweets[u'Body'] = tweets[u'Body'].astype(str)

tweets[u'Body'] = tweets[u'Body'].apply(lambda x:demoji(x))

weets[u'Body'] = tweets[u'Body'].apply(lambda x:demoji(x))

#Preprocessing del RT @blablabla:
tweets['tweetos'] = '' 

#add tweetos first part
for i in range(len(tweets['Body'])):
    try:
        tweets['tweetos'][i] = tweets['Body'].str.split(' ')[i][0]
    except AttributeError:    
        tweets['tweetos'][i] = 'other'

#Preprocessing tweetos. select tweetos contains 'RT @'
for i in range(len(tweets['Body'])):
    if tweets['tweetos'].str.contains('@')[i]  == False:
        tweets['tweetos'][i] = 'other'# remove URLs, RTs, and twitter handles
for i in range(len(tweets['Body'])):
    tweets['Body'][i] = " ".join([word for word in tweets['Body'][i].split()
                                if 'http' not in word and '@' not in word and '<' not in word])

这段代码是去除特殊字符,如/n,Twitter提及,基本上是文本清理

【问题讨论】:

  • 我可能完全错了,但你应该看看 python 中的线程。也许这会有所帮助

标签: python pandas dataframe


【解决方案1】:

每当您使用 Pandas 并开始迭代数据框内容时,很有可能您的方法缺乏。尝试坚持使用经过高度优化的原生 Pandas 工具/方法!另外,请注意重复:在您的代码中,您一遍又一遍地做一些事情。例如。 在每次迭代中

  • 1. 循环您拆分 df.Body (tweets['tweetos'][i] = tweets['Body'].str.split(' ')[i][0]),只从结果帧中选择一项
  • 2. 循环您评估框架的完整列 (tweets['tweetos'].str.contains('@')) 仅从结果中选择一项。

您的代码可能如下所示:

import pandas as pd
import re

df = pd.read_csv("data.csv")
tweets = df.replace(to_replace=[r"\\t|\\n|\\r", "\t|/n|/r|w/|\n|w/|Quote::"], value=["",""], regex=True)
# Why not tweets = df.replace(r'\\t|\\n|\\r|\t|/n|/r|w/|\n|w/|Quote::', ',') ?

re_emoji = re.compile(...) # As in your code
tweets.Body = tweets.Body.astype(str).str.replace(re_emoji, '') # Is the astype(str) necessary?
body_split = tweets.Body.str.split()
tweets['tweetos'] = body_split.map(lambda l: 'other' if not l else l[0])
tweets.tweetos[~tweets.tweetos.str.contains('@')] = 'other'
re_discard = re.compile(r'http|@|<')
tweets.Body = (body_split.map(lambda l: [w for w in l if not re_discard.search(w)])
                         .str.join(' '))

请注意,我对您正在使用的数据没有任何真正的洞察力 - 您没有提供样本。所以我提出的代码中可能存在错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 2012-12-16
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    相关资源
    最近更新 更多