How to order the values a pandas data frame based on the predefined array containing the desired order?

Indrajit :
df = pd.DataFrame({'id': [1, 2, 3, 4, 5],
 'p1': [0, 0, 1, 1, 2],
 'p2': [9, 2, 3, 5, 3],
 'p3': [1, 3, 10, 3, 7],
 'p4': [4, 4, 7, 1, 10]})

df = df.set_index('id')
df

    p1  p2  p3  p4
id                
1    0   9   1   4

2    0   2   3   4

3    1   3  10   7

4    1   5   3   1

5    2   3   7  10

Now suppose I have a data frame that contains the desired row-wise position for the each element of the df data frame. For example, say,

 order=np.argsort(-df.values,axis=1)

order
array([[1, 3, 2, 0],  
       [3, 2, 1, 0],  
       [2, 3, 1, 0],  
       [1, 2, 0, 3],  
       [3, 2, 1, 0]], dtype=int64)

How can I order the df dataframe elements based on the elements of the order array?

The desired result would be

    p1  p2  p3  p4
id                
1    9   4   1   0
2    4   3   2   0
3   10   7   3   1
4    5   3   1   1
5   10   7   3   2
Sameeresque :

Create a mapper like shown here, and then you can do like this:

mapper={0:'p1',1:'p2',2:'p3',3:'p4'}
df_copy=df.copy()
for index, row in df.iterrows():
    i=0
    for name, values in row.iteritems():

        df[name][index]=df_copy[mapper[order[index-1][i]]][index]
        i=i+1

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=169028&siteId=1