Re: Re: Replace non-numeric values in a list
- To: mathgroup at smc.vnet.net
- Subject: [mg88832] Re: [mg88786] Re: [mg88745] Replace non-numeric values in a list
- From: "Szabolcs HorvÃt" <szhorvat at gmail.com>
- Date: Sat, 17 May 2008 23:29:34 -0400 (EDT)
- References: <12929374.1210891275393.JavaMail.root@m08>
Here's yet another variation, that is slightly faster on my machine (we can negate the pattern instead of the test): In[7]:= Replace[bigriffledlist, Except[_?NumericQ] -> 0, 1]; // Timing Out[7]= {7.86, Null} In[8]:= Replace[bigriffledlist, {x_?NumericQ -> x, x_ -> 0}, 1]; // Timing (* Bobby's version *) Out[8]= {9.765, Null} On Sat, May 17, 2008 at 5:28 AM, Syd Geraghty <sydgeraghty at mac.com> wrote: > Hi Adel et al, > > There were a lot of interesting replies to this question. > > I thought you might be interested in speed of some of them on a big list. > > Bobby was fastest followed by Szabolcs. > > bigriffledlist = Riffle[RandomInteger[{1, 5}, 5000000], {x, y, z}]; > > newlistbob = Replace[bigriffledlist, {x_?NumericQ -> x, x_ -> 0}, 1]; // > Timing (* DrMajorBob *) > > {5.81391, Null} > > newlistszabolcs = Replace[bigriffledlist, x_ /; ! NumericQ[x] -> 0, 1]; // > Timing (*Szabolcs Horvat*) > > {8.11852, Null} > > > newlistszabolcs == newlistbob // Timing > > {0.090427, True} > > Other notables were. > > newlist = Map[(If[NumericQ[#], #, 0] &), bigriffledlist]; // Timing (*Bob > Hanlon*) > > {10.2462, Null} > > newlist = Replace[bigriffledlist, _?(Not[NumericQ[#]] &) -> 0, 1]; // > Timing (*Bob Hanlon*) > > {11.9771, Null} > > Cheers ... Syd > > Syd Geraghty B.Sc, M.Sc. > > sydgeraghty at mac.com > > My System > > Mathematica 6.0.2.1 for Mac OS X x86 (64 - bit) (March 13, 2008) > MacOS X V 10.5.2 > MacBook Pro 2.33 Ghz Intel Core 2 Duo 2GB RAM > > > > > > > On May 16, 2008, at 2:34 AM, DrMajorBob wrote: > >> list = {a, 1, 2, b, 3}; >> Replace[list, {x_?NumericQ -> x, x_ -> 0}, 1] >> >> {0, 1, 2, 0, 3} >> >> or >> >> Replace[list, x_ /; ! NumericQ[x] -> 0, 1] >> >> {0, 1, 2, 0, 3} >> >> Bobby >> >> On Thu, 15 May 2008 06:50:03 -0500, Adel Elsabbagh <aelsabbagh at gmail.com> >> wrote: >> >>> Dear all, >>> >>> I have a list that contains numeric and non-numeric values >>> list = { a, 1, 2, b, 3}; >>> How can I replace non-numeric values with zeros? >>> Thanks! >>> >> >> >> >> -- >> >> DrMajorBob at longhorns.com >> > >