4
$\begingroup$

I really love the addition of Dataset to Mathematica. I would like to write a basic utility function that exports a Dataset to Excel.

Is there a way to get a list of column names from a Dataset?

$\endgroup$
4
  • 2
    $\begingroup$ For a flat dataset Keys acting on the first row should work. $\endgroup$ Jan 16, 2015 at 22:27
  • $\begingroup$ @SjoerdC.deVries Could you please explain what you mean by a flat Dataset? Do you mean one where the keys are just primitive types? $\endgroup$ Jan 16, 2015 at 22:28
  • 1
    $\begingroup$ @Shredderroy just a rectangular row x column type of dataset, not one of the fancier types that have embedded structures and such. Basically the first category shown under the Applications heading in the documentation. $\endgroup$ Jan 16, 2015 at 22:30
  • $\begingroup$ @SjoerdC.deVries, even a "flat" row x column dataset can have embedded structures. Dataset doesn't preclude eg, Graphics in some or all cells. Of course, that wouldn't really use Dataset lookup. Nested Associations allow use of Query. $\endgroup$ Jan 17, 2015 at 18:32

1 Answer 1

6
$\begingroup$

Just an example:

tab = Table[{If[PrimeQ[i], "type" -> "Prime", "type" -> "NoPrime"], 
"n" -> i, "dc" -> DigitCount[i!, 2, 1], 
"dc1" -> DigitCount[i! + 1, 2, 1]}, {i, 20, 40}];

make a Dataset:

ds = Dataset[Association @@@ tab]

get the column heads:

First@Keys@ds

You can then make a table, export, to Excel, or whatever. Excel Export of the values can be done e.g. with

temp = Normal@ds[All, {"type", "n", "dc"}] // Values

and

Export["test.xls", temp]

If necessary you can Prepend the column heads to get them into Excel, too.

$\endgroup$
3
  • $\begingroup$ mgamer - thank you most kindly! I will give this a shot. $\endgroup$ Jan 17, 2015 at 14:27
  • 1
    $\begingroup$ For performance purposes I think it is better to use Keys@First@ds. $\endgroup$ Feb 16, 2017 at 15:12
  • $\begingroup$ @AntonAntonov: Absolutely right :-) $\endgroup$
    – mgamer
    Jun 30, 2019 at 15:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.