首页 > 解决方案 > sort pandas DataFrame with a column with list

问题描述

I want to sort the rows of this dataframe based on the first value of the array in the "boxes" column 0.8299769, 0.04913859 in descending order. How can I do it.

  classes              boxes                                scores
0   7     [0.8299769, 0.27715018, 0.91143125, 0.54477763]   0.999721
2   7     [0.04913859, 0.35264254, 0.15933079, 0.64380944]  0.999397

标签: pythonpandasdataframesorting

解决方案


try this, create psuedo column sort sort based on it & drop

df = pd.DataFrame({"classes": [7, 2], "boxes": [[0.04913859, 0.35264254, 0.15933079, 0.64380944],
                                                [0.8299769, 0.27715018, 0.91143125, 0.54477763]],
                   "scores": [0.999721, 0.999397]})

df['sort'] = df['boxes'].apply(lambda x: x[0])

df.sort_values(by='sort', ascending=False).drop(columns=['sort'])

   classes                                             boxes    scores
1        2   [0.8299769, 0.27715018, 0.91143125, 0.54477763]  0.999397
0        7  [0.04913859, 0.35264254, 0.15933079, 0.64380944]  0.999721

推荐阅读