Milo Ventimiglia
Milo Ventimiglia

Reputation: 91

Add row after the last element of a group

Concerning pandas, I have 2 dataframes:

Dataframe 1:
0 | a | 0
1 | a | 1
2 | a | 2
3 | b | 0
4 | b | 2
5 | c | 0
6 | c | 7
... (it continues)

Dataframe 2:
0 | a | x
1 | b | y
2 | c | z
... (it continues)

Dataframe1:
I need to add x,y after the last element of each group in dataframe1. The resulting dataframe shall look like this:

Resulting dataframe:
0 | a | 0
1 | a | 1
2 | a | 2
3 | a | x
4 | b | 0
5 | b | 2
6 | b | y
...

Any ideas? Many thanks!

Upvotes: 1

Views: 108

Answers (1)

jezrael
jezrael

Reputation: 862691

If values in df1 are sorted by first column, then use concat + sort_values + reset_index:

df = pd.concat([df1,df2]).sort_values('a').reset_index(drop=True)
print (df)
    a   b
0   a   0
1   a   1
2   a   2
3   a   x
4   b   0
5   b   2
6   b   y
7   c   0
8   c   7
9   c   z

For sorting values in df1 use:

df1 = df1.sort_values('a')

Input:

print (df1)
   a  b
0  a  0
1  a  1
2  a  2
3  b  0
4  b  2
5  c  0
6  c  7

print (df2)
    a   b
0   a   0
1   a   1
2   a   2
3   a   x
4   b   0
5   b   2
6   b   y
7   c   0
8   c   7
9   c   z
10  c  z1

Another solution by comment of Corley Brigman:

df = pd.concat([df1.set_index('a'),df2.set_index('a')]).sort_index().reset_index()
print (df)
    a   b
0   a   0
1   a   1
2   a   2
3   a   x
4   b   0
5   b   2
6   b   y
7   c   0
8   c   7
9   c   z
10  c  z1

Upvotes: 1

Related Questions