[英]Pandas df reorder rows and columns according to integer index list
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]
.现在我得到两个列表,一个具有重新排序的列索引,一个具有重新排序的行索引,但是作为整数,例如
rowindices = [3,1,2]
和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
:使用
DataFrame.iloc
并且因为 python 从0
计数,将列表转换为数组并减去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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.