I have a pandas dataframe with N columns. I want to reorder it such that last two…
- User
I have a pandas dataframe with N columns. I want to reorder it such that last two columns come to beginning.
Assistant
You can use the
ilocmethod in pandas to reorder the columns of a dataframe. To move the last two columns to the beginning, you can follow these steps:- Identify the indexes of the last two columns by using the
-2and-1index slices. - Use
ilocto select the columns in the desired order, with the last two columns at the beginning.
Here's an example:
import pandas as pd # Create a sample dataframe df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9], 'D': [10, 11, 12] }) # Get the indexes of the last two columns last_two_cols = df.columns[-2:] # Reorder the dataframe with the last two columns at the beginning df_reordered = df[list(df.columns[:-2]) + last_two_cols] print(df_reordered)Output:
C D A B 0 7 10 1 4 1 8 11 2 5 2 9 12 3 6- Identify the indexes of the last two columns by using the
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.