1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Extracting text from a string in Pandas

Discussão em 'Python' iniciado por Stack, Setembro 15, 2024.

  1. Stack

    Stack Membro Participativo

    I'm trying to create two new columns by extracting text from strings in an existing column in a Pandas dataframe.

    Dataframe

    I would like to create two new columns from portions of stings in column Sample ID. I’m not great at regex and have been struggling to get the right expressions.


    1. I would like to extract the Sample ID name B/TP-1. This name will vary in the dataframe (B/TP-1, B/TP-2 and so on).


    2. I would like to extract the depth 0.5 from the Sample ID. These depths may vary in the dataframe (0.5, 2.5, 5, 10, 15 and so on).

    IN an attempt to extract the depth I’ve tried the following expression and several slightly different expressions, but it did not give me only the depth for each sample (see example output).

    pattern = r'B/TP-6-(\d+\d+)

    SAMPDATA_w['Sample ID2'] = SAMPDATA_w['Sample ID'].apply(lambda x: re.search(pattern, x) .group(1) if re.search(pattern, x) else None)


    Dataframe with attempted output

    I've also not been able extract just the sample ID.

    Continue reading...

Compartilhe esta Página