简体   繁体   中英

Find the increase, decrease in column of Dataframe group by an other column in Python / Pandas

In my dataframe i want to know if the ordonnee value are decreasing, increasing,or not changing, in comparison with the precedent value (the row before) and group by the column temps .

I already try the method of these post: stackoverflow post

And I try to groupby but this is not working do you have ideas?

entry = pd.DataFrame([['1',0,0],['1',1,1],['1',2,1],['1',3,1],['1',3,-2],['2',1,2],['2',1,3]],columns=['temps','abcisse','ordonnee'])

output = pd.DataFrame([['1',0,0,'--'],['1',1,1,'increase'],['1',2,1,'--'],['1',3,1,'--'],['1',3,-2,'decrease'],['2',1,2,'--'],['2',1,3,'increase']],columns=['temps','abcisse','ordonnee','variation'])

Use

In [5537]: s = entry.groupby('temps').ordonnee.diff().fillna(0)

In [5538]: entry['variation'] = np.where(s.eq(0), '--', 
                                         np.where(s.gt(0), 'increase',
                                         'decrease'))

In [5539]: entry
Out[5539]:
  temps  abcisse  ordonnee variation
0     1        0         0        --
1     1        1         1  increase
2     1        2         1        --
3     1        3         1        --
4     1        3        -2  decrease
5     2        1         2        --
6     2        1         3  increase

Also, as pointed in jezrael's comment, you can use np.select instead of np.where

In [5549]: entry['variation'] = np.select([s>0, s<0], ['increase', 'decrease'],
                                          default='--')

Details

In [5541]: s
Out[5541]:
0    0.0
1    1.0
2    0.0
3    0.0
4   -3.0
5    0.0
6    1.0
Name: ordonnee, dtype: float64

Use np.where with groupby transform ie

entry['new'] = entry.groupby(['temps'])['ordonnee'].transform(lambda x : \
                      np.where(x.diff()>0,'incresase',
                      np.where(x.diff()<0,'decrease','--')))

Output :

temps  abcisse  ordonnee        new
0     1        0         0         --
1     1        1         1  incresase
2     1        2         1         --
3     1        3         1         --
4     1        3        -2   decrease
5     2        1         2         --
6     2        1         3  incresase

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM