[Python] Using split on a column for subset of rows

Discussão em 'Python' iniciado por Stack, Maio 30, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to selectively parse rows based on a condition:

    df = pd.DataFrame({"a":["z|v", "b|3", "z|x", "dfe|5", "xs|2"]})
    df['x']=""
    df['y']=""

    mask = df['a'].str.startswith('z')
    print(mask)

    df.loc[mask, ['x', 'y']] = df.loc[mask, 'a'].str.split('|', n=1, expand=True)
    print(df)


    Outputs:

    a x y
    0 z|v NaN NaN
    1 b|3
    2 z|x NaN NaN
    3 dfe|5
    4 xs|2


    its returning NaNs.

    if I just apply:

    df[['x', 'y']] = df['a'].str.split('|', n=1, expand=True)


    it works for all rows:

    a x y
    0 z|v z v
    1 b|3 b 3
    2 z|x z x
    3 dfe|5 dfe 5
    4 xs|2 xs 2


    Any help appreciated.

    Continue reading...

Compartilhe esta Página