1

I use this (somewhat kludgy) R function to merge data.frames and keep the order of one of them:

MergeMaintainingOrder = function(Ordered,Unordered,ByWhatColumn){
  Ordered$TEMPINDEX = 1:length(Ordered[,1])
  MergedData = merge(Ordered,Unordered,by=ByWhatColumn)
  MergedData = MergedData[order(MergedData$TEMPINDEX),]
  MergedData$TEMPINDEX = NULL
  return(MergedData)
}

How can I accomplish the same thing in pandas? Is there a less kludgy way or should I just rewrite the same function?

Thanks,

-N

N. McA.
  • 4,796
  • 4
  • 35
  • 60

1 Answers1

1

In pandas a merge resets the index, but you can easily work around this by resetting the index before doing the merge. Resetting the index will create a new column called "index" which you can then use to re-create your index after the merge. For example:

Ordered.reset_index().merge(Ordered, Unordered, on=ByWhatColumn).set_index('index')

See this question/answer for more discussion (hat tip to @WouterOvermeire)

Community
  • 1
  • 1
Matti John
  • 19,329
  • 7
  • 41
  • 39