MathGroup Archive 2011

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: read CSV

  • To: mathgroup at smc.vnet.net
  • Subject: [mg117790] Re: read CSV
  • From: David Bailey <dave at removedbailey.co.uk>
  • Date: Thu, 31 Mar 2011 04:03:57 -0500 (EST)
  • References: <imus7l$i3t$1@smc.vnet.net>

On 30/03/2011 10:13, Alan wrote:
> I've received some files formatted like below.
> How can I read selected columns into a list?
> I'm coming from a background where I'd read in each line,
> discarding the first, then (in this case at least)
> split on the comma, and coerce the type.  So I'm happy
> to do that if I can figure out how.  (Naturally I could
> preprocess the data into a form that say ReadList
> likes better, but I'm looking for a pure Mathematica solution.)
>
> Thanks,
> Alan Isaac
>
> "x","y","color","pen down?"
> "0","0.26161459854014585","105","true"
> "1","0.2665251497682828","105","true"
> "2","0.29244385081680907","105","true"
> "3","0.31995416628471895","105","true"
>

Here is the code you need. Since you are new to Mathematica, I'll 
explain a bit.

1)  The Import command will read data from files using the filename 
suffix to decide the format it expects. Under Windows, a full pathname 
uses backslash characters, which need to be doubled in strings.

2)   The data is read in as a 2D array, which can be thought of as a 
list of rows - you need to drop one row.

3)   Assuming you want the string "true" to become a Mathematica 
boolean, you need the /. operator to perform the swap, as shown


In[2]:= data = Import["c:\\ttt\\test.csv"]

Out[2]= {{"x", "y", "color", "pen down?"}, {0, 0.261615, 105,
   "true"}, {1, 0.266525, 105, "true"}, {2, 0.292444, 105, "true"}, {3,
    0.319954, 105, "true"}}

In[5]:= data =
  Drop[data, 1] /. "true" -> True

Out[5]= {{2, 0.292444, 105, True}, {3, 0.319954, 105, True}}

David Bailey
http://www.dbaileyconsultancy.co.uk


  • Prev by Date: Re: Bloch Equation, NDSolve, and strange behaviors
  • Next by Date: Re: read CSV
  • Previous by thread: Re: read CSV
  • Next by thread: Re: read CSV