Skip to content

Commit baf02c7

Browse files
Added #sortByRowNamesUsing: with tests.
1 parent 822ae9d commit baf02c7

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

src/DataFrame-Tests/DataFrameTest.class.st

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5157,6 +5157,31 @@ DataFrameTest >> testSortByAll [
51575157
self assert: actual equals: expected
51585158
]
51595159

5160+
{ #category : #tests }
5161+
DataFrameTest >> testSortByRowNamesUsing [
5162+
"sorts by second letter of row name"
5163+
5164+
| dataFrame expected sortedDF |
5165+
dataFrame := DataFrame withRows:
5166+
#( #( 'CD' 3 2 )
5167+
#( 'AC' 1 4 )
5168+
#( 'DB' 2 4 )
5169+
#( 'BA' 5 1 ) ).
5170+
dataFrame rowNames: #( 'CD' 'AC' 'DB' 'BA' ).
5171+
5172+
expected := DataFrame withRows:
5173+
#( #( 'BA' 5 1 )
5174+
#( 'DB' 2 4 )
5175+
#( 'AC' 1 4 )
5176+
#( 'CD' 3 2 ) ).
5177+
expected rowNames: #( 'BA' 'DB' 'AC' 'CD' ).
5178+
5179+
sortedDF := dataFrame sortByRowNamesUsing: [ :name1 :name2 |
5180+
name1 second <= name2 second ].
5181+
5182+
self assert: sortedDF equals: expected
5183+
]
5184+
51605185
{ #category : #tests }
51615186
DataFrameTest >> testSortByUsing [
51625187
"Sort by second letter of city name"

src/DataFrame/DataFrame.class.st

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2469,6 +2469,22 @@ DataFrame >> sortByAll: arrayOfColumnNames [
24692469
^ self
24702470
]
24712471

2472+
{ #category : #sorting }
2473+
DataFrame >> sortByRowNamesUsing: aBlock [
2474+
"Sorts the rows of the data frame based on the row names using the given comparison block"
2475+
2476+
| sortedKeys newContents |
2477+
sortedKeys := self rowNames sorted: aBlock.
2478+
2479+
newContents := DataFrameInternal new: self dimensions.
2480+
2481+
sortedKeys withIndexDo: [ :key :i |
2482+
newContents rowAt: i put: (self row: key) asArray ].
2483+
2484+
contents := newContents.
2485+
self rowNames: sortedKeys
2486+
]
2487+
24722488
{ #category : #sorting }
24732489
DataFrame >> sortDescendingBy: columnName [
24742490
"Rearranges the rows of the data frame in descending order of the values in the column named columnName"

0 commit comments

Comments
 (0)