2

I have Pandas Dataframe named df. I want to replace each value in sentence column within start and end with X.

df = pd.DataFrame({'sentence': ['I eat chicken', 'I drive car'], 
                   'start': [3, 3],
                    'end': [6,8]})

For example that will return I X chicken and I X car in sentence column. I try using apply and replace, but it returns error.

2 Answers 2

1

Yes, you can apply, with just the correct function:

df.apply(lambda x: x.sentence[:x.start-1] + ' X ' + x.sentence[x.end:], axis=1)

Output:

0    I  X chicken
1        I  X car
dtype: object
Sign up to request clarification or add additional context in comments.

Comments

0

IIUC slice_replace

df.apply(lambda x : x.str.slice_replace(start=x['start']-1, stop=x['end']-1, repl='X'),1).sentence
0    I X chicken
1        I X car
Name: sentence, dtype: object

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.