【问题标题】:How to switch column values in the same Pandas DataFrame如何在同一个 Pandas DataFrame 中切换列值
【发布时间】:2020-08-07 05:56:14
【问题描述】:

我有以下数据框:

我需要用 col4 和 col5 的值切换 col2 和 col3 的值。 col1 的值将保持不变。最终结果需要如下所示:

有没有办法在不循环 DataFrame 的情况下做到这一点?

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    在熊猫中使用rename

    In [160]: df = pd.DataFrame({'A':[1,2,3],'B':[3,4,5]})
    
    In [161]: df
    Out[161]:
       A  B
    0  1  3
    1  2  4
    2  3  5
    
    In [167]: df.rename({'B':'A','A':'B'},axis=1)
    Out[167]:
       B  A
    0  1  3
    1  2  4
    2  3  5
    

    【讨论】:

      【解决方案2】:

      应该这样做:

      og_cols = df.columns
      new_cols = [df.columns[0], *df.columns[3:], *df.columns[1:3]]
      df = df[new_cols] # Sort columns in the desired order
      df.columns = og_cols # Use original column names
      

      【讨论】:

        【解决方案3】:

        如果要交换列值:

        df.iloc[:, 1:3], df.iloc[:, 3:] = df.iloc[:,3:].to_numpy(copy=True), df.iloc[:,1:3].to_numpy(copy=True)
        

        【讨论】:

          【解决方案4】:

          熊猫reindex 可以帮忙:

          cols = df.columns
          
          #reposition the columns
          df = df.reindex(columns=['col1','col4','col5','col2','col3'])
          #pass in new names
          df.columns = cols
          

          【讨论】:

            猜你喜欢
            • 2020-06-24
            • 2022-12-17
            • 1970-01-01
            • 2021-01-28
            • 2022-01-22
            • 2018-05-03
            • 2019-07-16
            • 1970-01-01
            相关资源
            最近更新 更多