Categorizing the list of array in python

耗尽温柔 提交于 2019-12-04 16:09:10

Firstly I would like to say that I don't understand one part of your question,

array([3,-2]) #decreasing value
array([-2,-4,-7]) #decreasing value

Why are these separate?

I will post my answer so far which gives the correct results except for that section since i don't see the logic behind it. This example uses lists and tuples for simplicity but you can change it to use array if you want.

>>> from itertools import groupby
>>> data = [0,1,2,3,4,3,2,3,-2,-4,-7,2,2]
>>> def slope(a,b): #Returns 1 for inc, 0 for equal and -1 for dec
        return (a > b) - (a < b) 

>>> def groups(nums):
        for k,v in groupby(zip(nums,nums[1:]), lambda (x,y): slope(x,y)):
            yield next(v) + tuple(y for x,y in v) #Using itertools.chain this can be written as tuple(chain(next(v),(y for x,y in v)))


>>> list(groups(data))
[(0, 1, 2, 3, 4), (4, 3, 2), (2, 3), (3, -2, -4, -7), (-7, 2), (2, 2)]

I find all the places where the runs change, then generate the runs including both endpoints.

def sgn(x):
  return (x > 0) - (x < 0)

def categorize(xs):
  endpoints = [0]
  endpoints.extend(i for i, x in enumerate(xs[1:-1], 1)
                   if sgn(x - xs[i - 1]) != sgn(xs[i + 1] - x))
  endpoints.append(len(xs) - 1)
  for e0, e1 in zip(endpoints, endpoints[1:]):
    yield xs[e0:e1 + 1]

print list(categorize([0,1,2,3,4,3,2,3,-2,-4,-7,2,2]))
print list(categorize([0, 1, 2, 3]))
print list(categorize([0]))

How about this one using numpy, it solves your second problem at the same time.

import numpy as np

x=(0, 1, 2, 3, 4, 3, 2, 3, -2, -4, -7, 2, 2)
y=range(13)

#First order differential, find slopes
dx = list((np.diff(x)>0)*1)

#First order differental looses first value, but we always want to keep it
#just decide if it's lower or higher than the 2nd value

d0=((x[0]-x[1])>0)*1

#Add the first order differential to the 2nd order differential (peaks)
ddx = [d0,]+list(np.abs(np.diff(dx)))

p=0
rx=[]
ry=[]

for n,v in enumerate(ddx):
    if v==1:
        rx.append(tuple(x[p:n+1]))
        ry.append(tuple(y[p:n+1]))
        p=n

print rx
print ry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!