I wrote a function that I use to preprocess pandas dataframes before running them through a machine learning model. The function works perfectly, however I don't think it's the most pythonic way to write it.
This function accepts a list of words:
['here', 'is', 'a','sample', 'of','what','the','function','accepts']
def clean_text(x):
stopwords_english = stopwords.words('english')
for i,word in enumerate(x):
if word.lower() in stopwords_english:
x[i] = ''
else:
for punct in "/-'":
x[i] = word.replace(punct, ' ')
for punct in '&':
x[i] = word.replace(punct, f' {punct} ')
for punct in '?!.,"#$%\'()*+-/:;<=>@[\\]^_`{|}~' + '“”’':
x[i] = word.replace(punct, '')
return x
Here I am using enumerate
to change the value inside of the list. I would have assumed a more pythonic way of doing it would be writing it as follows:
def clean_text(x):
stopwords_english = stopwords.words('english')
for word in x:
if word.lower() in stopwords_english:
word = ''
else:
for punct in "/-'":
word = word.replace(punct, ' ')
for punct in '&':
word = word.replace(punct, f' {punct} ')
for punct in '?!.,"#$%\'()*+-/:;<=>@[\\]^_`{|}~' + '“”’':
word = word.replace(punct, '')
return x
The function is being called as follows:
train['question_text'].progress_apply(lambda x: clean_text(x))
Where train
is a pandas dataframe and 'question_text' is a column in the dataframe.
Is my current implementation the most pythonic way, or is there a better way?
clean_text
topandas.Series
sequence? Post a context of calling \$\endgroup\$train['question_text']
column contains a list of words in each cell , imagine that after replacement the resulting list could have multiple gaps like['', 'is', 'a','', 'of','what','the','','']
- is that expected in your case? or the result could be returned as a plain text ? \$\endgroup\$'&'
with regex that looks for an ampersand that isn't surrounded by spaces. \$\endgroup\$