0

Converted a column of a Pandas dataframe to list. Then lowercased all the elements in the list. Now want to keep only alphabets in the elements of the list. I wrote a regular expression for that. The regex is not working.

df_smer_orig = pd.read_csv('sample.csv', engine='python')
df_smer = df_smer_orig['Item'].tolist()
df_smer = [x.lower() for x in df_smer] 

for x in df_smer:
    print(x)
    regex = re.compile('[^a-zA-Z]')
    regex.sub('', x)
    print(x)

print(df_smer)

Partial output of the code which shows the regex did not work:

agarbathi / incense sticks
agarbathi / incense sticks
worcestershire sauce- 295ml
worcestershire sauce- 295ml

2 Answers 2

1

Your code is correct but you have to assign the result back to the variable get the desired output.

df_smer_orig = pd.read_csv('sample.csv', engine='python')
df_smer = df_smer_orig['Item'].tolist()
df_smer = [x.lower() for x in df_smer] 

for x in df_smer:
    print(x)
    regex = re.compile('[^a-zA-Z]')
    x = regex.sub('', x)
    print(x)

print(df_smer)
Sign up to request clarification or add additional context in comments.

Comments

1

Is that right?

text = re.sub(r'[^a-zA-Z]', '', text)

demo: http://tpcg.io/ZADE7f

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.