[Python] Update dataframe cell based on row criteria

Discussão em 'Python' iniciado por Stack, Abril 21, 2025.

  1. Stack

    Stack Membro Participativo

    Let's say I have the following dataframe:

    +----+------------------------------------------------+-------------+----------+----------+
    | | String | Substring | Result 1 | Result 2 |
    +----+------------------------------------------------+-------------+----------+----------+
    | 0 | fooDisplay "screen 1" other text | Screen 1 | | |
    | 1 | foobar Display "Screen2" more text | GFX | | |
    | 2 | barDisplay "Screen2"useless text | Screen 2 | | |
    | 3 | Link="Screen 1" | Screen 1 | | |
    +----+------------------------------------------------+-------------+----------+----------+


    I am trying to achieve the following:

    +----+------------------------------------------------+-------------+----------+----------+
    | | String | Substring | Result 1 | Result 2 |
    +----+------------------------------------------------+-------------+----------+----------+
    | 0 | foo"Display screen 1" other text | Screen 1 | True | False |
    | 1 | foobar Display "Screen2" more text | GFX | False | False |
    | 2 | barDisplay "Screen2"useless text | Screen 2 | False | True |
    | 3 | Link="Screen 1" | Screen 1 | False | False |
    +----+------------------------------------------------+-------------+----------+----------+


    From a pseudocode standpoint, this is what I am trying to do:

    search_string = 'Display ' + row['Substring']
    if row['String'].containsCaseInsensitive search_string:
    row['Result 1'] = True
    else:
    row['Result 1'] = False

    search_string2 = 'Display "' + row['Substring'] + '"'
    if row['String'].containsCaseInsensitive search_string2:
    row['Result 2'] = True
    else:
    row['Result 2'] = False


    I know that I can accomplish this by iterating through each row, but I am trying to be a good Python user and avoid that as I have hundreds of thousands of rows in my dataframe, and multiple "Result" columns (upwards of 10) in some cases.

    I see plenty of examples online where "static" substrings are located within a dataframe string, however, I can't seem to find an example that uses the contents of a dataframe cell as the substring used to search another cell in the same row. Here is one such example: pandas-case-insensitive-in-a-string-or-case-ignore

    So, how do I efficiently update dataframe rows using a combination of dynamic and static queries for a given row?

    Continue reading...

Compartilhe esta Página