1

Please I have dataframe with four columns that are [keys, summary, description, and summary_description], so iam dealing with summary_description, trying to apply RegEx and extract the new result in a [New_column], so I have done the looping but Iam not sure what is the problem not working getting error. Please if anyone could help, I would really appreciate it.

import pandas as pd
import re
dataf= pd.read_excel(r'C:\Users\malotaibi\Desktop\Last update\result.xlsx')
dataf
dataf.head(5)
dataf['New_Column'][i] = re.sub('[^A-Za-z0-9]+', ' ', dataf['Summary_Description'][i])
print (dataf['New_column'][i])

Error:

KeyError: 'New_Column'
2
  • You should do print(dataf.columns), it'll show you the columns you have access to. It says there is no column New_Column with a capital C. Check it again. Commented Jul 2, 2019 at 14:00
  • iam not sure if my loop is correct ot not, but I did what you said print(dataf.columns), is still the same problem, iam using jupyter. thanks Commented Jul 2, 2019 at 14:06

2 Answers 2

1

You can do it like this:

dataf['New_Column'] = dataf['Summary_Description'].str.replace('[^A-Za-z0-9]+', ' ')

Sign up to request clarification or add additional context in comments.

Comments

0

You have tried to add to the 'New Column' key before creating it. So do

import pandas as pd
import re
dataf= pd.read_excel(r'C:\Users\malotaibi\Desktop\Last update\result.xlsx')
dataf
dataf.head(5)
dataf['New_Column'] = 1 # this will create the new_column entry and set all its values to 1

You can now loop through this and set each value to what you want. I assume you're going for something like:

for i in range(len(dataf['Summary_Description'])):
    dataf['New_Column'][i] = re.sub('[^A-Za-z0-9]+', ' ', dataf['Summary_Description'][i])

2 Comments

Thank you so much Kathy for your time, it really helped.
No worries, though I'd like to point out the answer below given by PraveenB is much cleaner and also works, but its up to you

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.