0

I am able to change the sequence of columns using below code I found on stackoverflow, now I am trying to convert it into a function for regular use but it doesnt seem to do anything. Pycharm says local variable df_name value is not used in last line of my function.

Working Code

columnsPosition = list(df.columns)
F, H = columnsPosition.index('F'), columnsPosition.index('H')
columnsPosition[F], columnsPosition[H] = columnsPosition[H], columnsPosition[F]
df = df[columnsPosition]

My Function - Doesnt work, need to make this work

def change_col_seq(df_name, old_col_position, new_col_position):
    columnsPosition = list(df_name.columns)
    F, H = columnsPosition.index(old_col_position), columnsPosition.index(new_col_position)
    columnsPosition[F], columnsPosition[H] = columnsPosition[H], columnsPosition[F]
    df_name =  df_name[columnsPosition] # pycharm has issue on this line

I have tried adding return on last statement of function but I am unable to make it work.

  • 2
    Does this [link](https://stackoverflow.com/questions/57446160/swap-or-exchange-column-names-in-pandas-dataframe-with-multiple-columns) answer your question ? – SunilG Jun 08 '21 at 07:43
  • also have a look [here](https://stackoverflow.com/questions/25649429/how-to-swap-two-dataframe-columns) – julian Jun 08 '21 at 13:25

1 Answers1

2

To re-order the Columns

To change the position of 2 columns:

def change_col_seq(df_name:pd.DataFrame, old_col_position:str, new_col_position:str):
    df_name[new_col_position], df_name[old_col_position] = df_name[old_col_position].copy(), df_name[new_col_position].copy()
    df = df_name.rename(columns={old_col_position:new_col_position, new_col_position:old_col_position})
    return df

To Rename the Columns

You can use the rename method (Documentation)

If you want to change the name of just one column:

def change_col_name(df_name, old_col_name:str, new_col_name:str):
    df = df_name.rename(columns={old_col_name: new_col_name})
    return df

If you want to change the name of multiple column:

def change_col_name(df_name, old_col_name:list, new_col_name:list):
    df = df_name.rename(columns=dict(zip(old_col_name, new_col_name)))
    return df
99_m4n
  • 1,239
  • 3
  • 17
  • I apologize for the confusion, but I need to move the whole column (change its sequence) not rename them. I will update my question and change parameter names to more accurately reflect. – Muhammad Ali Jun 08 '21 at 11:15
  • I have edited the answer to switch the position of 2 columns – 99_m4n Jun 08 '21 at 12:30