[Python] Is there a way to select the entire arbitrary string value in a pandas data frame and...

Discussão em 'Python' iniciado por Stack, Julho 15, 2025.

  1. Stack

    Stack Membro Participativo

    I have a data frame with a variety of string values. For a given column, if there is any string entered, I would like to replace it with the same value (say 'present').

    Example:

    data = {'item_name': ['apple', 'banana', 'cherry', 'pineapple', 'apple pie', 'banana split', 'hafts to chos', 'lov_frutz', 'I always pick apples', None, None, None]}
    df = pd.DataFrame(data)


    Result I want:

    item_name
    'fruit'
    'fruit'
    'fruit'
    'fruit'
    'fruit'
    'fruit'
    'fruit'
    'fruit'
    'fruit'
    nan
    nan
    nan

    response = 'fruit'


    I have tried using regex but don't seem to understand it correctly, so tried:

    df[col] = df[col].replace(to_replace=r'\w\b', value = response, regex = True)

    Continue reading...

Compartilhe esta Página