Using the following example dataframe:
a <- c(1:5) b <- c("Cat", "Dog", "Rabbit", "Cat", "Dog") c <- c("Dog", "Rabbit", "Cat", "Dog", "Dog") d <- c("Rabbit", "Cat", "Dog", "Dog", "Rabbit") e <- c("Cat", "Dog", "Dog", "Rabbit", "Cat") f <- c("Cat", "Dog", "Dog", "Rabbit", "Cat") df <- data.frame(a,b,c,d,e,f)
I want to investigate how to reorder the columns WITHOUT having to type in all the column names, i.e., df[,c("a","d","e","f","b","c")]
How would I just say I want columns b and c AFTER column f? (only referencing the columns or range of columns that I want to move?).
Many thanks in advance for your help.
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.
order() is used to rearrange the dataframe columns in alphabetical order.
You can change the order of columns in the pandas dataframe using the df. reindex() method.
Just use double brackets and insert the columns you want to shift.
To move specific columns to the beginning or end of a data.frame, use select
from the dplyr package and its everything()
function. In this example we are sending to the end:
library(dplyr) df %>% select(-b, -c, everything()) a d e f b c 1 1 Rabbit Cat Cat Cat Dog 2 2 Cat Dog Dog Dog Rabbit 3 3 Dog Dog Dog Rabbit Cat 4 4 Dog Rabbit Rabbit Cat Dog 5 5 Rabbit Cat Cat Dog Dog
Without the negation, the columns would be sent to the front.
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