[Python] Expand and then sort dataframe based on the value order in the first row

Discussão em 'Python' iniciado por Stack, Março 16, 2025.

  1. Stack

    Stack Membro Participativo

    Suppose I have a dataframe with the following format of strings separated by commas:

    index columnName
    0 apple,peach,orange,pear,
    1 orange, pear,apple
    2 pear
    3 peach,apple
    4 orange

    The actual number rows will be greater than 10,000.

    I want to expand the dataframe and sort the dataframe by row 0.

    My expected output is below, where None is NoneType:

    index 0 1 2 3
    0 apple peach orange pear
    1 apple None orange pear
    2 None None None pear
    3 apple peach None None
    4 None None orange None

    I have expand the data

    df= df['columnName'].str.split(',',expand=True) #expand initial dataframe


    I cannot sort/reorder the data as desired despite trying various combinations of df.sort_values().

    Continue reading...

Compartilhe esta Página