How to sort each list entry in pandas column?

Viewed 26

I'm attempting to sort a column in a pandas dataframe where each column contains a list of numbers.

For example :

import pandas as pd
import numpy as np
  
# creating the Numpy array
array = np.array([[1, [2,1,3]], [2,[3,1,2]]])
  
# creating a list of index names
index_values = ['first', 'second']
   
# creating a list of column names
column_values = ['id', 'list']
  
# creating the dataframe
df = pd.DataFrame(data = array, 
                  index = index_values, 
                  columns = column_values)
  
# displaying the dataframe
print(df)

renders :

enter image description here

Here I attempt to ascending sort the column list so that each entry is transformed to :

[1,2,3]
[1,2,3]

using code :

def sort_col(col):
    col.sort

df['list'] = df.apply(lambda x: sort_col(x['list']), axis=1)

df.head()

but the following is rendered and the list is not sorted :

enter image description here

How to sort asscending each list entry in the pandas column ?

1 Answers

Use sorted with column list is simpliest way:

df['list'] = df['list'].apply(sorted)
print(df)

       id       list
first   1  [1, 2, 3]
second  2  [1, 2, 3]

Your solution working if add return, because sort inplace modify list:

def sort_col(col):
    col.sort()
    return col

df['list'] = df.apply(lambda x: sort_col(x['list']), axis=1)

print(df)
       id       list
first   1  [1, 2, 3]
second  2  [1, 2, 3]

def sort_col(col):
    col.sort()
    return col
df['list'] = df['list'].apply(sort_col)
Related