Reputation: 109
I have a dataframe that roughly looks like this
ID VAL
2 3
2 7
2 4
2 5
2 2
3 4
3 6
3 7
3 2
4 2
4 3
4 4
4 5
4 6
Another dataframe that roughly looks like this
ID VAL
2 5
3 7
I want to do an operation that for each row in the second dataframe, the row will move to the top.
ID VAL
2 5
2 3
2 7
2 4
2 2
3 7
3 4
3 6
3 2
4 2
4 3
4 4
4 5
4 6
See that the (2, 5) tuple and the (3, 7) tuple have been moved up to where that "ID" begins.
I've currently a horribly inefficient implementation.
Any help would be appreciated!
Upvotes: 2
Views: 28
Reputation: 323316
I am using a help key create by using merge
then we sort_values
df1.merge(df2.assign(key=0),how='left').fillna({'key':1}).sort_values(['ID','key'])
# you can add .drop('key',1) at the end :-)
ID VAL key
3 2 5 0.0
0 2 3 1.0
1 2 7 1.0
2 2 4 1.0
4 2 2 1.0
7 3 7 0.0
5 3 4 1.0
6 3 6 1.0
8 3 2 1.0
9 4 2 1.0
10 4 3 1.0
11 4 4 1.0
12 4 5 1.0
13 4 6 1.0
Upvotes: 3