【问题标题】:How do I reverse the column values and leave the column headers as they are如何反转列值并保持列标题不变
【发布时间】:2026-02-09 12:35:02
【问题描述】:

假设我有一个数据框df

df = pd.DataFrame([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]],
                  columns=['A', 'B', 'C', 'D', 'E'])

看起来像这样

   A  B  C  D   E
0  1  2  3  4   5
1  6  7  8  9  10

如何颠倒列值的顺序,但将列标题保留为 A、B、C、D、E?

我希望它看起来像

    A  B  C  D  E
0   5  4  3  2  1
1  10  9  8  7  6

我尝试对列索引df.sort_index(1, ascending=False) 进行排序,但这会改变列标题(显然),而且我不知道我的列是否以排序方式开始。

【问题讨论】:

    标签: python pandas numpy dataframe


    【解决方案1】:

    或者您可以反转您的列:

    df.columns = reversed(df.columns)
    df.sortlevel(axis=1)
    
    #   A   B   C   D   E
    #0  5   4   3   2   1
    #1  10  9   8   7   6
    

    【讨论】:

    • 这个答案很棒!要获得与以前相同的顺序,我会df.reindex_axis(reversed(df.columns)) 或类似的东西。
    • @piRSquared 是的,reindex_axis 在这里可能是一个更好的解决方案。
    【解决方案2】:

    方法 1
    重构

    pd.DataFrame(df.values[:, ::-1], df.index, df.columns)
    

    方法 2
    赋值

    df[:] = df.values[:, ::-1]
    df
    

    都给

    【讨论】:

      【解决方案3】:

      另外,使用np.fliplr 沿水平方向翻转值:

      pd.DataFrame(np.fliplr(df.values), columns=df.columns, index=df.index)
      

      【讨论】: