我有两个数据帧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)
从图中可以看出,我希望B像A一样重新排列
让我们试试
或者我们试试
pd.Categorical
您可以使用reindex-like将两个数据帧的索引设置为“title”,使用
A
重新索引B
,也可以使用普通reindex,然后重置索引:您还可以使用
merge
:如果您想要索引,类似于@BENY接受的答案,您可以组合take和get_indexer_for-如果您的索引是唯一的,您可以使用get_indexer:
相关问题 更多 >
编程相关推荐