Skip to content

Commit 9b5f8fb

Browse files
Added DataFrame>> #toString. Fixed #126.
1 parent be3db59 commit 9b5f8fb

2 files changed

Lines changed: 50 additions & 0 deletions

File tree

src/DataFrame-Tests/DataFrameTest.class.st

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5199,6 +5199,19 @@ DataFrameTest >> testToMarkdown [
51995199
self assert: df toMarkdown equals: expectedString
52005200
]
52015201

5202+
{ #category : #tests }
5203+
DataFrameTest >> testToString [
5204+
5205+
| expectedString |
5206+
expectedString := '# City Population BeenThere
5207+
''A'' ''Barcelona'' 1.609 true
5208+
''B'' ''Dubai'' 2.789 true
5209+
''C'' ''London'' 8.788 false
5210+
'.
5211+
5212+
self assert: df toString equals: expectedString
5213+
]
5214+
52025215
{ #category : #tests }
52035216
DataFrameTest >> testTransposed [
52045217

src/DataFrame/DataFrame.class.st

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2432,6 +2432,43 @@ DataFrame >> toMarkdown [
24322432
^ markdown contents
24332433
]
24342434

2435+
{ #category : #converting }
2436+
DataFrame >> toString [
2437+
" Prints the DataFrame as a String formatted table"
2438+
2439+
| stringTable columnWidths dataFrame |
2440+
dataFrame := self copy.
2441+
dataFrame addColumn: dataFrame rowNames named: '#' atPosition: 1.
2442+
stringTable := WriteStream on: String new.
2443+
2444+
columnWidths := dataFrame columnNames collect: [ :columnName |
2445+
| maxWidth |
2446+
maxWidth := columnName size.
2447+
dataFrame rows do: [ :row |
2448+
| value |
2449+
value := row at: columnName.
2450+
maxWidth := maxWidth max: value printString size ].
2451+
maxWidth ].
2452+
2453+
dataFrame columnNames withIndexDo: [ :columnName :index |
2454+
| paddedColumnName |
2455+
paddedColumnName := columnName padRightTo: (columnWidths at: index).
2456+
stringTable nextPutAll: paddedColumnName, ' ' ].
2457+
stringTable cr.
2458+
2459+
2460+
2461+
dataFrame asArrayOfRows do: [ :row |
2462+
row withIndexDo: [ :value :index |
2463+
| paddedValue |
2464+
paddedValue := value printString padRightTo:
2465+
(columnWidths at: index).
2466+
stringTable nextPutAll: paddedValue , ' ' ].
2467+
stringTable cr ].
2468+
2469+
^ stringTable contents
2470+
]
2471+
24352472
{ #category : #geometry }
24362473
DataFrame >> transposed [
24372474
"Returns a transposed DataFrame. Columns become rows and rows become columns."

0 commit comments

Comments
 (0)