Python 如何基于外部索引对数据帧行重新排序

Python 如何基于外部索引对数据帧行重新排序,python,pandas,dataframe,Python,Pandas,Dataframe,我想根据外部映射对数据帧中的行重新排序。例如,如果列表是2,1,3,我想将旧df中的第一项移动到新df中的第二项。我认为我的问题与此相同:但这个解决方案不起作用。以下是我尝试过的: a = list(sampleinfo.filename) b = list(exprs.columns) matchIndex2 = [a.index(x) for x in b] (1) sampleinfo2 = sampleinfo[matchIndex2,] (2) sampleinf

我想根据外部映射对数据帧中的行重新排序。例如,如果列表是2,1,3,我想将旧df中的第一项移动到新df中的第二项。我认为我的问题与此相同:但这个解决方案不起作用。以下是我尝试过的:

a = list(sampleinfo.filename)
b = list(exprs.columns)
matchIndex2 = [a.index(x) for x in b]

(1)
    sampleinfo2 = sampleinfo[matchIndex2,]

(2) 
    sampleinfo2 = sampleinfo
    sampleinfo2.reindex(matchIndex2)
两个解决方案都没有出错,但顺序没有改变——就好像我什么都没做一样

我试图确保exprs中的列和sampleinfo中的行的文件名值的顺序相同。在我在线看到的解决方案中,我可以对EXPR的列进行排序:

a = list(sampleinfo.filename)
b = list(exprs.columns)
matchIndex = [b.index(x) for x in a]
exprs = exprs[matchIndex]
但我希望能够按行排序。我该怎么做

我正在使用的数据帧太大,无法粘贴,但一般情况如下:

exprs: 
a1 a2 a3 a4 a5 
1  2  2  2  1
4  3  2  1  1

sampleinfo:
filename   otherstuff
a1          fwsegs
a5          gsgers
a3          grsgs
a2          gsgs
a4          sgs

下面是一个使用绑定到数据框中特定列的外部列表对行重新排序的函数:

def reorder(A, column, values):
    """Re-order data frame based on a column (given in the parameter
       column, which must have unique values)"""
    if set(A[column]) != set(values):
        raise Exception("ERROR missing values for re-ordering")
    at_position = {}
    index = 0;
    for v in A[column]:
        at_position[v] = index
        index += 1
    re_position = [ at_position[v] for v in values ]
    return A.iloc[ re_position ];

您可以发布示例df和所需的输出,您可以使用另一个系列并调用reindex_like,或者添加一个临时列,按照您希望的顺序按该列排序,然后删除临时列column@EdChum我将尝试使用新的顺序创建临时列,但如何按非索引列进行排序?我意识到我可以将作为索引的列更改为重新编制索引,但这似乎很笨拙,而且即使有效也容易出错。似乎reindex_like也仅适用于索引列?添加一个临时列后,您可以将其命名为df.sorttemp_col_name,请参阅文档: