[Python] Trying to figure out why df.replace() is not working in a Pandas DF

Discussão em 'Python' iniciado por Stack, Agosto 9, 2025.

  1. Stack

    Stack Membro Participativo

    I am attempting to use df.replace() in pandas to replace all 0's in column sentiment_text['polarity'] with the string 'negative' and all 4's with the string 'positive' in the same column. I have tried the following code:

    sentiment_text['polarity'].replace('0', 'negative') sentiment_text['polarity'].replace('4', 'positive')

    and

    sentiment_text.replace({'polarity': {'0': 'negative'}, 'polarity': {'4': 'positive'}})

    When I run either of these, either nothing changes or only 0 or 4 changes to the correct string.

    Here is some sample data

    data = {'polarity': [0, 0, 0, 4, 4, 4],'text': ["is upset that he can't update his Facebook", 'my whole body feels itchy and like its on fire', 'bad dog', 'Having no school is the best feeling ever', 'Happy 38th Birthday to my boo of alll time!!!', 'Yahoo!!']}

    Continue reading...

Compartilhe esta Página