Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to figure out trend per unique key. dataframe

Tags:

python

pandas

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
like image 863
Mza Avatar asked Dec 14 '22 15:12

Mza


2 Answers

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
like image 69
Bharath Avatar answered Jan 01 '23 09:01

Bharath


Using diff and crosstab

s=df.groupby('ColA').ColB.diff().dropna()#Dropna since the first value for all group is invalid 
pd.crosstab(df.ColA.loc[s.index],s>0,normalize = 'index' )[True].map({1:'Up',0:'Down'}).fillna('Flat')
Out[100]:
ColA
A      Up
C    Flat
D      Up
L    Down
Name: True, dtype: object
like image 30
BENY Avatar answered Jan 01 '23 09:01

BENY