I have the following structure for my data frame:
col1 col2 col3
myindex
apple A B C
pear Ab Bb Cb
turtle A1 B1 C1
Now I get two lists, one with reordered column indices, one with reordered row indices, but as integers, for example rowindices = [3,1,2]
and colindices = [1,3,2]
. The data frame should now be reordered according to these indices and then look like this:
col1 col3 col2
myindex
turtle A1 C1 B1
apple A C B
pear Ab Cb Bb
How can this be done?
Use DataFrame.iloc
and because python counts from 0
convert list to arrays and subtract 1
:
rowindices = [3,1,2]
colindices = [1,3,2]
df = df.iloc[np.array(rowindices)-1, np.array(colindices)-1]
print (df)
col1 col3 col2
myindex
turtle A1 C1 B1
apple A C B
pear Ab Cb Bb
If is possible change values in lists solution is simplier:
rowindices1 = [2,0,1]
colindices1 = [0,2,1]
df = df.iloc[rowindices1, colindices1]
print (df)
col1 col3 col2
myindex
turtle A1 C1 B1
apple A C B
pear Ab Cb Bb
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.