根据原始数据帧对行重新排序

2024-09-30 22:22:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧A和B。B是A的副本。我对B做了一些操作,现在它们的结构都相同,只是B的所有行都按列“title”排序,例如:title0,title1…,而A的列“title”没有顺序,例如:title24,title13。。。。我想让B像A中的标题一样重新排列。我试图列出A的标题列,并对B进行了重新索引,这很管用,但后来我的标题列变成了B的索引列,这是我不想要的。任何帮助都将不胜感激。多谢各位

代码:

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

从图中可以看出,我希望B像A一样重新排列


Tags: 标题dataframetitlecol2pdtitle2tit41tit45
2条回答

让我们试试

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

或者我们试试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

您可以使用reindex-like将两个数据帧的索引设置为“title”,使用A重新索引B,也可以使用普通reindex,然后重置索引:

B.set_index("title").reindex_like(A.set_index("title")).reset_index()


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

您还可以使用merge

pd.merge(B, A["title"], how="right")

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

如果您想要索引,类似于@BENY接受的答案,您可以组合takeget_indexer_for-如果您的索引是唯一的,您可以使用get_indexer

B.take(pd.Index(A.title).get_indexer_for(B.title))

    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

相关问题 更多 >