Home > database >  Sort list of string numbers that are in a column of a data frame
Sort list of string numbers that are in a column of a data frame

Time:05-19

I have a data frame whose one column contains lists of string number

Col1
['1']
['1']
['1','3','4']
['2','3','1','4','5']

How can I sort this number? I have tried to adapt the answer given here.

I would like to have a sorted list of integers instead of strings.

CodePudding user response:

Try this

df = pd.DataFrame({'Col1':[['1'],['1'],['1','3','4'],['2','3','1','4','5']]})
# use a list comprehension in which map list elements to int and sort the list
df['sorted'] = [sorted(map(int, row)) for row in df['Col1']]
print(df)
              Col1           sorted
0              [1]              [1]
1              [1]              [1]
2        [1, 3, 4]        [1, 3, 4]
3  [2, 3, 1, 4, 5]  [1, 2, 3, 4, 5]

CodePudding user response:

Use:

In [599]: df['Col1'] = df.Col1.apply(lambda x: sorted(map(int, x)))
In [600]: df
Out[600]: 
              Col1
0              [1]
1              [1]
2        [1, 3, 4]
3  [1, 2, 3, 4, 5]
  • Related