How to map or sort values of two different dataframe?

Viewed 106

I have a simple dataframe1 with 32 raws like this :

tot
time 67
price 44
money 35
quality 10

and i have another dataframe2 like this:

france UK italy
price 33 67 87
time 42 57 98
quality 38 24 12
money 14 63 22

I would like to sort the values in my dataframe2 by the list in dataframe1, so time,price,money,quality.

I can do it manually setting and index for dataframe2, but there are a lots of columns, i would like to do this in automatic way.

Thanks

2 Answers

You still can sort_index just need pass the function with key

out = df2.sort_index(key=lambda x : df1.index.get_indexer(x))
Out[76]: 
         france  UK  italy
time         42  57     98
price        33  67     87
money        14  63     22
quality      38  24     12

IIUC and the structure of both dataframes is that time, price, quality, and money are in the index of both dataframes. Use,

df2.reindex(df.index)

Note: using the reindex method over loc because if for some reason, df1.index has value not in df2.index, reindex will return NaN were loc will give a KeyError.

Related