Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

python - Reorder rows according to the original dataframe

I have 2 dataframes A and B. B is a copy of A. I did some manipulation on B and now both have the identical structure except that, B has all the rows sorted by the column "title", eg: title0, title1..., whereas A has a column "title" that has no order, eg: title24, title13.... I want B to be rearranged like titles in A. I tried to make a list of title column of A and did a reindex on B, which did the trick but then my title column became the index column of B, which I don't want. Any help would be appreciated. Thank you.

Code:

title=['tit12','tit22','tit21','tit42','tit41','tit45','tit33','tit36','tit32']
col2=['a','b','c','d','e','f','g','h','i']
d={
    "title":title,
    "col2":col2,
}
A= pd.DataFrame(d)
title2=['tit12','tit21','tit22','tit32','tit33','tit36','tit41','tit42','tit45']
col22=['i','h','g','f','e','d','c','b','a']
d2={
    "title":title2,
    "col2":col22,
}
B= pd.DataFrame(d2)

enter image description here

As you can see from the picture, I want B to be rearranged like A.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Let us try

B = B.iloc[B.title.map(dict(zip(A.title,range(len(A)))))]

B
   title col2
0  tit12    i
2  tit22    g
1  tit21    h
8  tit45    a
6  tit41    c
7  tit42    b
4  tit33    e
3  tit32    f
5  tit36    d

Or we try pd.Categorical

B = B.iloc[pd.Categorical(B.title,A.title.unique()).argsort()]
   title col2
0  tit12    i
2  tit22    g
1  tit21    h
7  tit42    b
6  tit41    c
8  tit45    a
4  tit33    e
5  tit36    d
3  tit32    f

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...