Advertisement
elena1234

how to swap and replace columns in Python

Oct 13th, 2022 (edited)
654
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.78 KB | Source Code | 0 0
  1. # define function to swap columns
  2. def swap_columns(df, col1, col2):
  3.     col_list = list(df.columns)
  4.     x, y = col_list.index(col1), col_list.index(col2)
  5.     col_list[y], col_list[x] = col_list[x], col_list[y]
  6.     df = df[col_list]
  7.     return df
  8.  
  9. #swap points and rebounds columns
  10. all_ads_until_10_Oct = swap_columns(all_ads_until_10_Oct, 'Company', 'Location')
  11. all_ads_until_10_Oct
  12.  
  13. ######################################################
  14. # move column to specific place
  15. column_to_move = df_jobs.pop("Date")
  16. df_jobs.insert(0, "Date", column_to_move )
  17.  
  18. ######################################################
  19. replace the last column into index 1
  20. df_auto = df_auto[['Model', 'Price BGN', 'Year', 'Kilometers', 'Transmission', 'Engine_type', 'Horsepower',
  21.                   'Date']]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement