I have a dataframe, with the following columns, in this order;
'2','4','9','A','1','B','C'
I want the first 3 columns to be ABC but the rest it doesn't matter.
Output:
'A','B','C','3','2','9'... and so on
Is this possible?
(there are 100's of columns, so i can't put them all in a list
The basic idea to move a column in a pandas dataframe is to remove the column from its current place and insert it in the desired position. The pandas library offers many useful functions such as pop() and insert(). We will make use of these two functions to manipulate with our dataframe.
In order to reorder or rearrange the column in pandas python. We will be different methods. To reorder the column in ascending order we will be using Sort() function. To reorder the column in descending order we will be using Sort function with an argument reverse =True.
Let’s get right into the different methods to change the column order of a dataframe in Pandas. This is one of the simplest methods to change the order of the columns of a pandas DataFrame object. In this method, we simply pass the Python list of columns of the DataFrame in the desired order to the DataFrame object.
If you wanted to select multiple columns, you can include their names in a list: Additionally, you can slice columns if you want to return those columns as well as those in between. The same code we wrote above, can be re-written like this: Now, let’s take a look at the iloc method for selecting columns in Pandas.
This can be done by selecting the column as a series in Pandas. You can pass the column name as a string to the indexing operator. For example, to select only the Name column, you can write: Doing this, this returns the following:
We will be different methods. To reorder the column in ascending order we will be using Sort () function. To reorder the column in descending order we will be using Sort function with an argument reverse =True. let’s get clarity with an example.
You can try to reorder like this:
first_cols = ['A','B','C']
last_cols = [col for col in df.columns if col not in first_cols]
df = df[first_cols+last_cols]
cols = ['2','4','9','A','1','B','C']
df = pd.DataFrame(1, range(3), cols)
df
2 4 9 A 1 B C
0 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
2 1 1 1 1 1 1 1
sorted
with key
key = lambda x: (x != 'A', x != 'B', x != 'C')
df[sorted(df, key=key)]
A B C 2 4 9 1
0 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
2 1 1 1 1 1 1 1
Better suited for longer length of first column members
first_cols = ['A', 'B', 'C']
key = lambda x: tuple(y != x for y in first_cols)
df[sorted(df, key=key)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With