[Python] How to add value from a list as new column value in dataframe, if existing column...

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

  1. Stack

    Stack Membro Participativo

    I have a dataframe which looks like shown below:

    CALL_START IMSI
    0 24.07.2025 12:00:51 123456888888888
    1 24.07.2025 17:58:57 123456999999999
    2 24.07.2025 17:05:47 543214511111111
    3 24.07.2025 17:02:30 543214522222222
    4 24.07.2025 16:07:44 987654444444444
    5 24.07.2025 16:07:49 777777444444444


    Dataframe has tens of thousands of rows and list used for comparing values is pretty short, lets say it has one hundred elements with different element length (5 or 6 characters) as shown below:

    ['123456', '54321', '98765']


    I would like to check if values from IMSI column (which is an object type - str) startswith values from a list and if so to add new columns to dataframe, one having value from a list and other column as boolean value. Something like this:

    CALL_START IMSI BAN FLAG
    0 24.07.2025 12:00:51 123456888888888 123456 True
    1 24.07.2025 17:58:57 123456999999999 123456 True
    2 24.07.2025 17:05:47 543214511111111 54321 True
    3 24.07.2025 17:02:30 543214522222222 54321 True
    4 24.07.2025 16:07:44 987654444444444 98765 True
    5 24.07.2025 16:07:49 777777444444444 None False


    So if value from IMSI column starts with value from list, add that value to a dataframe and add True to new column FLAG, if value from IMSI column does not starts with any element from a list add None (or whatever, it can be empty string) and add False to FLAG

    It is also acceptable to have only matches (without FLAG column):

    CALL_START IMSI BAN
    0 24.07.2025 12:00:51 123456888888888 123456
    1 24.07.2025 17:58:57 123456999999999 123456
    2 24.07.2025 17:05:47 543214511111111 54321
    3 24.07.2025 17:02:30 543214522222222 54321
    4 24.07.2025 16:07:44 987654444444444 98765


    I know i can use pd.Series.str.startswith() but this approach returns only Series with True or False value.

    Continue reading...

Compartilhe esta Página