【问题标题】:What would be Python/pandas equivalent of this R code for rearranging columns of a dataframe? [duplicate]用于重新排列数据框列的 Python/pandas 与此 R 代码等效的是什么? [复制]
【发布时间】:2017-05-23 05:48:35
【问题描述】:
data<-data[c(8,1:7)]

基本上,将最后一列移到第一个位置。我如何在 Python 中仅使用列索引(最好在一行中)来做到这一点?

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    使用numpy.r_
    这是为了允许R 类似数组切片的语法。因此r_

    假设您的数据框名为df

    import numpy as np
    import pandas as pd
    
    df = df.iloc[:, np.r_[8, 1:7]]
    

    【讨论】:

      【解决方案2】:

      你可以使用.iloc[]:

      data = data.iloc[:, [7] + list(range(7))]
      

      或者:data = data[[7] + list(range(7))]


      请记住

      • 在 python 中,索引是从零开始的,而 R 是从一开始的;
      • R 使用向量进行索引,而 python 使用列表。

      【讨论】:

        【解决方案3】:
        data = data[[7,0,1,2,3,4,5,6]]
        

        如果你有很多列..

        data = data[list(df.columns.tolist()[-1]) + df.columns.tolist()[:-1]]
        

        【讨论】:

        • 我也有类似的想法。 JMO,但我认为在这种情况下,在这种情况下实际上最好用两行来做:(1)​​col = df.columns.tolist()(2)df = df[ col[-1:] + col[:-1] ]
        猜你喜欢
        • 1970-01-01
        • 2013-01-12
        • 2020-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-27
        • 1970-01-01
        • 2017-01-27
        相关资源
        最近更新 更多