my array subset method could be improved?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jim O'D

    #1

    my array subset method could be improved?

    Hi all

    I have an array a=array([2,3,1]).

    I want to extract an array with all the elements of a that are less than 0.

    Method 1.
    new = array([i for i in a if i < 0])

    Method 2.
    new = a[nonzero(a<0)]

    I'm using Numeric arrays but can't seem to find a function that does this.

    Am I missing a more obvious way to do it quickly?

    Thanks

    Jim
  • Juho Schultz

    #2
    Re: my array subset method could be improved?

    Jim O'D wrote:[color=blue]
    > Hi all
    >
    > I have an array a=array([2,3,1]).
    >
    > I want to extract an array with all the elements of a that are less than 0.
    >
    > Method 1.
    > new = array([i for i in a if i < 0])
    >
    > Method 2.
    > new = a[nonzero(a<0)]
    >
    > I'm using Numeric arrays but can't seem to find a function that does this.
    >
    > Am I missing a more obvious way to do it quickly?
    >
    > Thanks
    >
    > Jim[/color]

    new = Numeric.compres s(Numeric.less( a,0),a)

    Comment

    • Jim O'D

      #3
      Re: my array subset method could be improved?

      [color=blue]
      >
      > new = Numeric.compres s(Numeric.less( a,0),a)[/color]

      Ah, thank you!

      Sorry about subject mangle, I gave a silly example first time round.

      Jim

      Comment

      • Peter

        #4
        Re: my array subset method could be improved?

        Jim O'D wrote:
        [color=blue]
        >Hi all
        >
        >I have an array a=array([2,3,1]).
        >
        >I want to extract an array with all the elements of a that are less than 0.
        >
        >Method 1.
        >new = array([i for i in a if i < 0])
        >
        >Method 2.
        >new = a[nonzero(a<0)]
        >
        >I'm using Numeric arrays but can't seem to find a function that does this.
        >
        >Am I missing a more obvious way to do it quickly?
        >
        >Thanks
        >
        >Jim
        >
        >[/color]
        You could use filter (which is planned to be removed in Py3000). E.g.
        "array(filter(l ambda x: x < 0, (-1, 2, -4, 5, 55, 9, -73, 5)))"

        I tend to like "array(i for i in (-1, 2, -4, 5, 55, 9, -73, 5) if i <
        0)" better though. (And its even shorter).

        HTH,
        Peter

        Comment

        • malik

          #5
          any good midi tutorials?

          anybody know any good midi tutorials for python?
          i am trying to make a realtime midi manipulation application.

          Comment

          Working...