【问题标题】:Flip DataFrame column order by keeping the Index通过保持索引来翻转 DataFrame 列顺序
【发布时间】:2020-11-02 01:24:08
【问题描述】:

我有一个类似的问题:Reverse DataFrame Column, But Maintain the Index

反转行可以正常工作:

import pandas as pd
df = pd.DataFrame(data=[[1,2,3],[4,5,6],[7,8,9]])
df.iloc[:] = df.iloc[::-1].values

如何反转列以获得此结果

   0  1  2
0  3  2  1
1  6  5  4
2  9  8  7

【问题讨论】:

    标签: python pandas dataframe reverse flip


    【解决方案1】:

    通过添加,将反向传递到列

    df.iloc[:] = df.iloc[:,::-1].values
    df
       0  1  2
    0  3  2  1
    1  6  5  4
    2  9  8  7
    

    【讨论】:

      【解决方案2】:

      您可以使用numpy flip 反转列:

      pd.DataFrame(np.flip(df.to_numpy()))
      
          0   1   2
      0   3   2   1
      1   6   5   4
      2   9   8   7
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-03
        • 2016-09-30
        • 1970-01-01
        • 2015-03-05
        • 2021-06-09
        • 2019-06-12
        相关资源
        最近更新 更多