>>> df =DataFrame({'a':[1,2,3,4],'b':[2,4,6,8]}) >>> df['x']=df.a + df.b >>> df['y']=df.a - df.b >>> df a b x y 0 1 2 3 -1 1 2 4 6 -2 2 3 6 9 -3 3 4 8 12 -4
Now I want to rearrange the column sequence, which makes 'x','y' column to be the first & second columns by :
>>> df = df[['x','y','a','b']] >>> df x y a b 0 3 -1 1 2 1 6 -2 2 4 2 9 -3 3 6 3 12 -4 4 8
But if I have a long coulmns 'a','b','c','d'....., and I don't want to explictly list the columns. How can I do that ?
Or Does Pandas provide a function like set_column_sequence(dataframe,col_name, seq)
so that I can do : set_column_sequence(df,'x',0)
and set_column_sequence(df,'y',1)
?
You need to create a new list of your columns in the desired order, then use df = df[cols] to rearrange the columns in this new order.
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.
You could also do something like this:
df = df[['x', 'y', 'a', 'b']]
You can get the list of columns with:
cols = list(df.columns.values)
The output will produce something like this:
['a', 'b', 'x', 'y']
...which is then easy to rearrange manually before dropping it into the first function
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