Search code examples
pythonpandassortingnested-lists

Order nested lists inside column


I have this dataset:

df = pd.DataFrame({'Name':['John', 'Rachel', 'Adam','Joe'],
                   'Age':[95, 102, 31,np.nan],
                   'Scores':[np.nan, [80, 82, 78], [25, 20, 30, 60, 21],np.nan]
                  })

I would like to sort values inside column 'scores'.

Desired output:

 Name    Age     Scores
John    95.0     NaN
Rachel  102.0    [78,80,82]
Adam    31.0     [20,21,25,30,60]
Joe     NaN      NaN

I have tried the solutions from this answer, as well as the code

df.sort_values(by=["Scores"], na_position="first")

but result wasn not the deisred one.


Solution

  • Drop the null values then map with sorted

    df['Scores'] = df['Scores'].dropna().map(sorted)
    

         Name    Age                Scores
    0    John   95.0                   NaN
    1  Rachel  102.0          [78, 80, 82]
    2    Adam   31.0  [20, 21, 25, 30, 60]
    3     Joe    NaN                   NaN