Get next row after groupby
Question:
My question is similar to this one : Get next row besides the previous row after groupby but not quite the same. I’d like to get the first row appearing after a group concatenated to each row of the group.
So if I have:
ID value counts date
1 1 3 1/2/2020
1 2 10 10/2/2020
1 3 5 15/2/2020
2 1 6 3/4/2020
2 2 2 10/4/2020
I’d like to have:
ID value counts date NextID NextValue NextCounts NextDate
1 1 3 1/2/2020 2 1 6 3/4/2020
1 2 10 10/2/2020 2 1 6 3/4/2020
1 3 5 15/2/2020 2 1 6 3/4/2020
2 1 6 3/4/2020 3 4 1 11/12/2020
2 2 2 10/4/2020 3 4 1 11/12/2020
3 4 1 11/12/2020 nan nan nan nan
Answers:
You can use a merge
on the groupby.first
+shift
:
out = df.merge(df.groupby('ID', sort=False).first()
.assign(ID=lambda d: d.index).shift(-1)
.add_prefix('Next').iloc[:-1],
left_on='ID', right_index=True, how='left')
Output:
ID value counts date Nextvalue Nextcounts Nextdate NextID
0 1 1 3 1/2/2020 1.0 6.0 3/4/2020 2.0
1 1 2 10 10/2/2020 1.0 6.0 3/4/2020 2.0
2 1 3 5 15/2/2020 1.0 6.0 3/4/2020 2.0
3 2 1 6 3/4/2020 4.0 1.0 11/12/2020 3.0
4 2 2 2 10/4/2020 4.0 1.0 11/12/2020 3.0
5 3 4 1 11/12/2020 NaN NaN NaN NaN
My question is similar to this one : Get next row besides the previous row after groupby but not quite the same. I’d like to get the first row appearing after a group concatenated to each row of the group.
So if I have:
ID value counts date
1 1 3 1/2/2020
1 2 10 10/2/2020
1 3 5 15/2/2020
2 1 6 3/4/2020
2 2 2 10/4/2020
I’d like to have:
ID value counts date NextID NextValue NextCounts NextDate
1 1 3 1/2/2020 2 1 6 3/4/2020
1 2 10 10/2/2020 2 1 6 3/4/2020
1 3 5 15/2/2020 2 1 6 3/4/2020
2 1 6 3/4/2020 3 4 1 11/12/2020
2 2 2 10/4/2020 3 4 1 11/12/2020
3 4 1 11/12/2020 nan nan nan nan
You can use a merge
on the groupby.first
+shift
:
out = df.merge(df.groupby('ID', sort=False).first()
.assign(ID=lambda d: d.index).shift(-1)
.add_prefix('Next').iloc[:-1],
left_on='ID', right_index=True, how='left')
Output:
ID value counts date Nextvalue Nextcounts Nextdate NextID
0 1 1 3 1/2/2020 1.0 6.0 3/4/2020 2.0
1 1 2 10 10/2/2020 1.0 6.0 3/4/2020 2.0
2 1 3 5 15/2/2020 1.0 6.0 3/4/2020 2.0
3 2 1 6 3/4/2020 4.0 1.0 11/12/2020 3.0
4 2 2 2 10/4/2020 4.0 1.0 11/12/2020 3.0
5 3 4 1 11/12/2020 NaN NaN NaN NaN