how to figure out trend per unique key. dataframe

  • A+
Category:Languages

I have a DataFrame with 2 cols

 ColA| ColB  D 2  D 12  D 15  A 20  A 40  A 60  C 60  C 55  C 70  C 45  L 45  L 23  L 10  L 5  

RESULT/Output would be

 D UP A UP C FLAT L Down  

Where UP is result of adding up all the relevant Weights: each successive weight for each key, must be less than the previous weight. Example for UP you must have

 


Here's a simple technique, might not suit for all cases i.e :

def sum_t(x):     # Compare the value with previous value     m = x > x.shift()      # If all of them are increasing then return Up     if m.sum() == len(m)-1:         return 'UP'     # if all of them are decreasing then return Down     elif m.sum() == 0:         return 'DOWN'     # else return flat     else:         return 'FLAT'  df.groupby('ColA')['ColB'].apply(sum_t) 

Output:

ColA A      UP C    FLAT D      UP L    DOWN Name: ColB, dtype: object 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: