Replace Pandas Dataframe Value Based on Index Range

Evan :

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.

Quang Hoang :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=387114&siteId=1