1
$\begingroup$

I exported a list (with two columns) to a .csv file with Mathematica, and the first few lines are,

-3.141592653589793,-942.4277659056601-7.514067804073956*^-12*I
-3.141592653589793,155.66354907107547-5.760593016133258*^-13*I
-3.141592653589793,-101.00525445626336-1.443383665316593*^-14*I

To export, I used the command

Export["table.csv", a]

When I import this table, Mathematica cannot interpret the complex numbers in the second column properly. How do I properly import this csv file into a table?

In[1]:= a = Import["table.csv"];

In[2]:= a[[1]]

Out[2]= {-3.14159, "-942.4277659056601-7.514067804073956*^-12*I"}

In[3]:= Re[a[[1]]]

Out[3]= {-3.14159, Re["-942.4277659056601-7.514067804073956*^-12*I"]}
$\endgroup$

1 Answer 1

1
$\begingroup$

This should interpret the complex number strings:

blist = ToExpression[#] & /@ a
{{-3.14159, -942.428 - 7.51407*10^-12 I}, {-3.14159, 
  155.664 - 5.76059*10^-13 I}, {-3.14159, -101.005 - 
   1.44338*10^-14 I}}
$\endgroup$
4
  • $\begingroup$ It works. Could you explain the meaning of the syntax ToExpression[#] & /@? $\endgroup$ Oct 12, 2021 at 15:04
  • 1
    $\begingroup$ ToExpression[#]& is a pure function with one slot called #. This is where the input goes. The & is the end of the function. The /@ is Mapping this function to each item in the list a. In plain English: Convert the string encountered to an Mma expression as you walk down the list a. If a list is encountered it changes its elements to expressions. $\endgroup$
    – Syed
    Oct 12, 2021 at 15:09
  • $\begingroup$ @Syed Why not ToExpression /@ a? $\endgroup$
    – MarcoB
    Oct 13, 2021 at 2:26
  • $\begingroup$ @MarcoB The shortened form is indeed better. Thanks for sharing your knowledge. $\endgroup$
    – Syed
    Oct 13, 2021 at 14:16

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.