Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

concatenate the next row to the previous row pandas

'''
#Input
 doc  sent col1 col2 col3
0   0    0    5   4    8
1   0    1    6   3    2
2   0    2    1   2    9
3   1    0    6   1    6
4   1    1    5   1    5

#Required Output
   doc  sent  col1  col2  col3  ncol1  ncol2  ncol3  pcol1  pcol2  pcol3
0    0     0     5     4     8      6      3      2      0      0      0
1    0     1     6     3     2      1      2      9      5      4      8
2    0     2     1     2     9      0      0      0      6      3      2
3    1     0     6     1     6      5      1      5      0      0      0
4    1     1     5     1     5      0      0      0      6      1      6
'''
#Code
cs = ['col1', 'col2', 'col3']
g = df.groupby('doc')

pd.concat([
   df, 
   g[cs].shift(-1).add_prefix('n'), 
   g[cs].shift().add_prefix('p')
], axis=1).fillna(0).astype(int)
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #concatenate #row #previous #row #pandas
ADD COMMENT
Topic
Name
8+7 =