Skip to content

Commit 7c70f3c

Browse files
Added DataFrame>> #toMarkdown along with tests
1 parent 2175378 commit 7c70f3c

2 files changed

Lines changed: 58 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
@@ -5133,6 +5133,19 @@ DataFrameTest >> testToColumnsAtApplyElementwise [
51335133
self assert: df equals: expected
51345134
]
51355135

5136+
{ #category : #tests }
5137+
DataFrameTest >> testToMarkdown [
5138+
5139+
| expectedString |
5140+
expectedString := '| # | City | Population | BeenThere |
5141+
| --- | ----------- | ---------- | --------- |
5142+
| ''A'' | ''Barcelona'' | 1.609 | true |
5143+
| ''B'' | ''Dubai'' | 2.789 | true |
5144+
| ''C'' | ''London'' | 8.788 | false |
5145+
'.
5146+
self assert: df toMarkdown equals: expectedString
5147+
]
5148+
51365149
{ #category : #tests }
51375150
DataFrameTest >> testTransposed [
51385151

src/DataFrame/DataFrame.class.st

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2259,6 +2259,51 @@ DataFrame >> toColumnsAt: arrayOfColumnNumbers applyElementwise: aBlock [
22592259
self toColumnAt: each applyElementwise: aBlock ]
22602260
]
22612261

2262+
{ #category : #converting }
2263+
DataFrame >> toMarkdown [
2264+
" Prints the DataFrame as a Markdown formatted table"
2265+
2266+
| markdown columnWidths |
2267+
self addColumn: self rowNames named: '#' atPosition: 1.
2268+
markdown := WriteStream on: String new.
2269+
markdown nextPutAll: '| '.
2270+
2271+
columnWidths := self columnNames collect: [ :columnName |
2272+
| maxWidth |
2273+
maxWidth := columnName size.
2274+
self rows do: [ :row |
2275+
| value |
2276+
value := row at: columnName.
2277+
maxWidth := maxWidth max: value printString size ].
2278+
maxWidth ].
2279+
2280+
self columnNames withIndexDo: [ :columnName :index |
2281+
| paddedColumnName |
2282+
paddedColumnName := columnName padRightTo: (columnWidths at: index).
2283+
markdown nextPutAll: paddedColumnName , ' | ' ].
2284+
markdown cr.
2285+
markdown nextPutAll: '| '.
2286+
2287+
columnWidths do: [ :width |
2288+
| secondRow |
2289+
secondRow := '-'.
2290+
width - 1 timesRepeat: [ secondRow := secondRow , '-' ].
2291+
markdown nextPutAll: secondRow , ' | ' ].
2292+
2293+
markdown cr.
2294+
2295+
self asArrayOfRows do: [ :row |
2296+
markdown nextPutAll: '| '.
2297+
row withIndexDo: [ :value :index |
2298+
| paddedValue |
2299+
paddedValue := value printString padRightTo:
2300+
(columnWidths at: index).
2301+
markdown nextPutAll: paddedValue , ' | ' ].
2302+
markdown cr ].
2303+
2304+
^ markdown contents
2305+
]
2306+
22622307
{ #category : #geometry }
22632308
DataFrame >> transposed [
22642309
"Returns a transposed DataFrame. Columns become rows and rows become columns."

0 commit comments

Comments
 (0)