2017-04-21 89 views
0

假设你有以下的数据框(这是更复杂)如何按索引对数据框的列进行排序?大熊猫

df4=pd.DataFrame(np.matrix([[1,5],[3,2],[4,3],[5,4],[2,1]]),index=['a','b','c','d','e']) 

这已经是排名,不过,我想通过行索引排名使其达到所需的数据帧作为

df5=pd.DataFrame(np.matrix([['a','e'],['e','b'],['b','c'],['c','d'],['d','a']])) 

有没有简单的方法呢?

非常感谢您

回答

0

我想排名基于索引的矩阵。我认为,解决方案发布不适合我的问题

我不得不写一个公式来回答这个问题

def Column_rank_based_list(f): 
    r,c=f.shape 
    B= array(range(r*c), dtype='a5').reshape(r,c) 
    for j in range(c): 
     for i in range(r): 
      B[f.ix[i,j]-1,j]=f.index[i] 
    return pd.DataFrame(B, columns=f.columns) 

不过,我有困难,因为它的条目之前打印湾

例如,对于

df4=pd.DataFrame(np.matrix([[1,5],[3,2],[4,3],[5,4],[2,1]]),index=['a','b','c','d','e']) 

你会获得

Column_rank_based_list(df4) 
4

df4作为索引器的df4指数:

pd.DataFrame(df4.index[df4-1]) 

注意,因为大熊猫的索引,我减去1从df4是从零开始的,但你的数据帧似乎是1基于。

所得输出:

0 1 
0 a e 
1 c b 
2 d c 
3 e d 
4 b a