1

I have a dataframe column of strings. Now I want to replace specific words in these strings with a value from another dataframe which has the meaning of the word to be replaced. I am currently using iterrrows() which takes about 2 minutes for 25000 rows. I would like to know if there is a more efficient way of doing this.

syn = pd.ExcelFile("C:/Key-Value.xlsx")
df_syn = syn.parse("Keys")

for idx, row in df_syn.iterrows():  
    df['col'] = df['col'].str.replace(r"\b"+row['synonym']+r"\b", row['word']) 

1 Answer 1

1

IIUC:

Setup

df_syn = pd.DataFrame(dict(synonym=['hug', 'kiss'], word=['warm', 'tender']))
df = pd.DataFrame(dict(col=['I want a hug', 'a kiss would be great']))

print(df_syn, df, sep='\n\n')

  synonym    word
0     hug    warm
1    kiss  tender

                     col
0           I want a hug
1  a kiss would be great

Solution

mapping = df_syn.assign(
    synonym=df_syn.synonym.radd(r'\b').add(r'\b')
).set_index('synonym').word.to_dict()

df.replace({'col': mapping}, regex=True)

                       col
0            I want a warm
1  a tender would be great
Sign up to request clarification or add additional context in comments.

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.