0
$\begingroup$

I would like to export an array to a csv file with a specific type of delimiter and a specific notation of the numbers (in this case scientific notation 1.234E-02).

How can I achieve this in a general form?

I now there is (reference: How to export CSV from Mathematica?)

Export["dataset.csv", dataset, "CSV"]

but I do not know how to change the delimiter (reference for similar problem: Comma issue from number point in csv export! - is there a nicer way now?) and the notation of the numbers in the csv file seems arbitrary. I would like to have something like a format specifier for the numbers. In particular I would like to have something like 1.234E-02 for the numbers format (which I guess is referred to as scientific).

$\endgroup$
3
$\begingroup$

This should do the trick (for example, if you would like to use a semicolon as a field separator):

dataset = Table[i^2 - 10.*j, {i, 10}, {j, 10}];
Export["dataset.csv", dataset/.x_?NumberQ:>ToString[ScientificForm[x, 10, NumberFormat -> (Row[{#1, If[#3 == "", #3, "E"], #3}] &)]], "Table", "FieldSeparators" -> ";"]

Depending on the structure of your dataset, you might need to apply ScientificForm to its members separately (or only some of them, or only numeric ones).

The advantage of "Table" over "CSV" is that the separator is not fixed to comma, but can be changed. See also the documentation:

http://reference.wolfram.com/language/ref/NumberFormat.html

http://reference.wolfram.com/language/ref/format/Table.html

$\endgroup$
  • 1
    $\begingroup$ Remember that ScientificForm is a wrapper which changes the printed format, but not the actual values. So ToString is necessary to actually output the numbers in scientific form for exporting. See here for details. Also, this NumberFormat function as is will print 2E if your exponent is 0. You might want to consider using this function after NumberFormat if you want to avoid this: (Row[{#1, If[#3 == "", #3, "E"], #3}] &) $\endgroup$ – Musang Oct 19 '16 at 14:53
  • $\begingroup$ This is a really good comment. Could you give a revised version of the command of the original answer, @Musang ? $\endgroup$ – Asking Questions Oct 19 '16 at 15:19
  • $\begingroup$ I queued an edit with your desired change. I also forgot to add the replacement operation in the Export which is necessary so that dataset is exported as a list of numbers, allowing proper formatting. $\endgroup$ – Musang Oct 19 '16 at 16:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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