Skip to content

Commit 30e829f

Browse files
committed
Merge pull request #168 from dsten/to-csv
Add to_csv method
2 parents 0492137 + 72c1d97 commit 30e829f

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

datascience/tables.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1314,6 +1314,35 @@ def to_df(self):
13141314
"""Convert the table to a Pandas DataFrame."""
13151315
return pandas.DataFrame(self._columns)
13161316

1317+
def to_csv(self, filename):
1318+
"""Creates a CSV file with the provided filename.
1319+
1320+
The CSV is created in such a way that if we run
1321+
``table.to_csv('my_table.csv')`` we can recreate the same table with
1322+
``Table.read_table('my_table.csv')``.
1323+
1324+
Args:
1325+
``filename`` (str): The filename of the output CSV file.
1326+
1327+
Returns:
1328+
None, outputs a file with name ``filename``.
1329+
1330+
>>> job = ['a', 'b', 'c', 'd']
1331+
>>> wage = [10, 20, 15, 8]
1332+
>>> some_table = Table([job, wage], ['job', 'wage'])
1333+
>>> some_table
1334+
job | wage
1335+
a | 10
1336+
b | 20
1337+
c | 15
1338+
d | 8
1339+
>>> some_table.to_csv('my_table.csv') # doctest: +SKIP
1340+
<outputs a file called my_table.csv in the current directory>
1341+
"""
1342+
# We use index = False to avoid the row number output that pandas does
1343+
# by default.
1344+
self.to_df().to_csv(filename, index = False)
1345+
13171346
def to_array(self):
13181347
"""Convert the table to a NumPy array."""
13191348
dt = np.dtype(list(zip(self.column_labels,

docs/tables.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ Exporting / Displaying
113113
Table.index_by
114114
Table.to_array
115115
Table.to_df
116+
Table.to_csv
116117

117118
Visualizations
118119

0 commit comments

Comments
 (0)