Mathematica - import CSV columns and processes?

I have a CSV file that is formatted like this:

0.0023709,8.5752e-007,4.847e-008 

and I would like to import it into Mathematica, and then each column is divided into a list so that I can do some math in the selected column.

I know that I can import data with:

 Import["data.csv"] 

then I can split the columns as follows:

 StringSplit[data[[1, 1]], ","] 

which gives:

 {"0.0023709", "8.5752e-007", "4.847e-008"} 

Now the problem is that I don’t know how to get the data into separate lists, and also Mathematica does not accept scientific notation in the form 8.5e-007.

Any help on how to break the data into columns and format scientific notation would be great.

Thanks in advance.

+4
source share
4 answers

KennyTM is correct.

 data = Import["data.csv", "CSV"]; column1 = data[[All,1]] column2 = data[[All,2]] ... 
+12
source

You can correct the notation using StringReplace[] .

 In[1]: aa = {"0.0023709", "8.5752e-007", "4.847e-008"}; In[2]: ToExpression[ StringReplace[ #, RegularExpression@ "(^\d+\.\d+)e([+-]\d+)" -> "$1*10^$2" ] ] & @ aa Out[2]: {0.0023709, 8.5752*10^-7, 4.847*10^-8} 

You can put the entire data array instead of aa for processing, all at once with one layer

 {col1,col2,col3} = ToExpression[...] & @ Transpose[Import["data.csv", "CSV"]]; 

with ToExpression[...] as above.

+2
source

Davorak's answer is correct if you need to import the entire CSV file as an array. However, if you have one line to convert from C / Fortran exponential notation, you can use ImportString with different arguments for the format. As an example there

 In[1]:= ImportString["1.0e6", "List"] Out[1]= {1.*^6} 

The operator *^ equivalent to Mathematica for e . Please note that this is also a good way to split lines that are in CSV form:

 In[2]:= ImportString["1.0e6,3.2,foo", "CSV"] Out[2]= {{1.*10^6,3.2,foo}} 

In both cases, you will receive your answer wrapped in an additional level of list structure, which is quite easy to handle. However, if you are really sure that you have only one number, you can turn the string into a stream and use Read . This is cumbersome enough that I stuck with ImportString , however:

 In[3]:= Module[{stream = StringToStream["1.0e6"], number}, number = Read[stream, "Number"]; Close[stream]; number] Out[3]= 1.*10^6 
+2
source

In MMA7, I use the "elements" argument. In fact, I cannot even import a CSV file without specifying an element:

aa = Import ["data.csv", "Data"]

When you do this, all lines are automatically converted to expressions: Head / @ Flatten @aa - {Real, Real, ....}. In addition, β€œ8.5752e-007” becomes 8.5752 * 10 ^ 7, the legal expression of MMA.

The result of the import is a 1xn list {{...}}.

So, Transpose @aa gives a list of nx1 {{.}, {.}, ....}.

I think this is the format you like.

+1
source

Source: https://habr.com/ru/post/1305236/


All Articles