1

I have a dataframe like this,

d = {'ID': ["A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F"],


    'value': [23, 23, 52, 52, 36, 36, 46, 46, 9, 9, 110, 110]}

df = pd.DataFrame(data=d)

   ID  value
0   A     23
1   A     23
2   B     52
3   B     52
4   C     36
5   C     36
6   D     46
7   D     46
8   E      9
9   E      9
10  F    110
11  F    110

Basically, I replicate original data set(n rows). The dataframe I want to get seems like this,

   ID  value
0   A     23
1   B     23
2   B     52
3   C     52
4   C     36
5   D     36
6   D     46
7   E     46
8   E      9
9   F      9

Move column of value one unit down and remain all pairs of values. So, I lost first of A, last of F and last two value 110. Finally, I have 2n-2 rows.

Jiayu Zhang
  • 719
  • 7
  • 22

3 Answers3

2

I think need:

df = df.set_index('ID').shift().iloc[1:-1].reset_index()
print (df)
  ID  value
0  A   23.0
1  B   23.0
2  B   52.0
3  C   52.0
4  C   36.0
5  D   36.0
6  D   46.0
7  E   46.0
8  E    9.0
9  F    9.0
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
2

I think this will solve your problem

import pandas as pd

d = {'ID': ["A", "A", "B", "B", "C", "C", "D", "D", "E", "E","F","F"],
    'value': [23, 23, 52, 52, 36, 36, 46, 46, 9, 9, 110, 110]}

df = pd.DataFrame(data=d)

df['value']=df['value'].shift(1)

df2=df[1:11] #here 11 is n-1,it depends on number of rows

print(df2)
Community
  • 1
  • 1
Harshmeet
  • 21
  • 4
0

So if you just want to shift ID by -1 and exclude last 2 rows:

df['ID'] = df['ID'].shift(-1)
result = df[:-2]
zipa
  • 27,316
  • 6
  • 40
  • 58