Pandas unable to split on multiple asterisk

Viewed 122

I'm trying to split on 5x asterisk in Pandas by reading in data that looks like this

"This place is not good ***** less salt on the popcorn!"

My code attempt is trying to read in the reviews column and get the zero index

review = review_raw["reviews"].str.split('*****').str[0]
print(review)

The error

sre_constants.error: nothing to repeat at position 0

My expectation

This place is not good 
2 Answers

pandas.Series.str.split

Series.str.split(pat=None, n=- 1, expand=False)

Parameters: patstr, optional String or regular expression to split on. If not specified, split on whitespace.

* character is a part of regex string which defines zero or more number of occurrences, and this is the reason why your code is failing.

You can either try escaping the character:

>>df['review'].str.split('\*\*\*\*\*').str[0]
0    This place is not good 
Name: review, dtype: object

Or you can just pass the regex:

>>df['review'].str.split('[*]{5}').str[0]
0    This place is not good 
Name: review, dtype: object

Third option would be to use inbuilt str.split() instead of pandas' Series.str.split()

>>df['review'].apply(lambda x: x.split('*****')).str[0]
0    This place is not good 
Name: review, dtype: object

Try out with this code

def replace_str(string):
    return str(string).replace("*****",',').split(',')[0]



review = review_raw["reviews"].apply(lambda x:replace_str(x))

Well suppose we already have a ',' in our input string in that case the code can be little tweaked like below. Since I am replacing ***** , I can replace with any character like '[' in the modified answer.

def replace_str(string):
    return str(string).replace("*****",'[').split('[')[0]



review = review_raw["reviews"].apply(lambda x:replace_str(x))
Related