python - Pandas df 根据整数索引列表对行和列重新排序

标签 python pandas dataframe

我的数据框具有以下结构:

          col1    col2   col3
 myindex
 apple    A       B      C
 pear     Ab      Bb     Cb
 turtle   A1      B1     C1

现在我得到两个列表,一个具有重新排序的列索引,一个具有重新排序的行索引,但是作为整数,例如 rowindices = [3,1,2]colindices = [1,3,2] .数据框现在应该根据这些索引重新排序,然后看起来像这样:
          col1   col3   col2
 myindex
 turtle   A1     C1     B1
 apple    A      C      B
 pear     Ab     Cb     Bb

如何才能做到这一点?

最佳答案

使用 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

如果可能,列表解决方案中的更改值更简单:
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

关于python - Pandas df 根据整数索引列表对行和列重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59861580/

相关文章:

python - 将每个 python 字典值除以总值

python - 如何即时生成文件并在下载后将其删除?

python - 过滤 Pandas 行,其中列中的第一个字母是/不是某个值

python - 找出 pandas 数据框中事件的中间出现的 "0"和第一次出现的 '' 1"

python - 如何将日期时间中的日期更改为当月的第一天

python - 不知道这个 : "pymysql.err.ProgrammingError: (1064..." 发生了什么

python (openpyxl) : Put data from one excel file to another (template file) & save it with another name while retaining the template

python - 计算 DataFrame 2x2 行列组的平均值

python - 根据 pandas 的得分列确定游戏的获胜者

python - 在追加到 pandas 数据框时创建新列