1
$\begingroup$

I have the following SparseArray:

s = SparseArray[ {{1, 1} -> 1, {1, 2} -> 2, {1, 3} -> 3, {2, 1} -> 4, {2, 2} -> 5, {2, 3} -> 6, {3, 1} -> 7, {3, 2} -> 8, {3, 3} -> 9}]; 

I label it as follow:

TableForm[s, TableHeadings -> {{"A", "B", "C"}, {"E", "F", "G"}}] 

I can then export this to csv as,

Export["Desktop/test.csv", TableForm[s, TableHeadings -> {{"A", "B", "C"}, {"A", "B", "C"}}]] 

yet doing this does not preserve the heading labels. I wonder how can I keep them in the csv file?

$\endgroup$
4
  • 2
    $\begingroup$ Use TableHeadings -> ... as option to Export. $\endgroup$ Commented Jan 9, 2020 at 15:30
  • $\begingroup$ @Alx thanks, can you please expand? I am not sure how to used this as option, my last command had the tableheadings so I'm not sure how else to keep it as option. $\endgroup$ Commented Jan 9, 2020 at 15:35
  • 3
    $\begingroup$ This works for me: Export["test.csv", s, "TableHeadings" -> {{"A", "B", "C"}, {"E", "F", "G"}}], help page on CSV has similar example of using "TableHeadings". $\endgroup$ Commented Jan 9, 2020 at 15:42
  • $\begingroup$ @Alx, I think your comment is worthy of an answer! It's true that the "TableHeadings" option for Export is in the docs, but I for one was not aware of it. and had not even thought of looking. $\endgroup$ Commented Jan 10, 2020 at 3:19

1 Answer 1

4
$\begingroup$

As suggested by @MarcoB in comments, I post my comment as answer.

In the documentation on CSV format one can find that Export command to this format has an option "TableHeadings", so we can use this to keep headings in exported file:

Export["test.csv", s, "TableHeadings" -> {{"A", "B", "C"}, {"E", "F", "G"}}] 

"","E","F","G" "A",1,2,3 "B",4,5,6 "C",7,8,9

$\endgroup$
1
  • $\begingroup$ Thank you for posting it! (+1) $\endgroup$ Commented Jan 11, 2020 at 3:18

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.