I'm trying to rearrange columns in a DataFrame, by putting a few columns first, and then all the others after.
With R's dplyr, this would look like:
library(dplyr)
df = tibble(col1 = c("a", "b", "c"),
id = c(1, 2, 3),
col2 = c(2, 4, 6),
date = c("1 Feb", "2 Feb", "3 Feb"))
df2 = select(df,
id, date, everything())
Easy. With Python's pandas, here's what I've tried:
import pandas as pd
df = pd.DataFrame({
"col1": ["a", "b", "c"],
"id": [1, 2, 3],
"col2": [2, 4, 6],
"date": ["1 Feb", "2 Feb", "3 Feb"]
})
# using sets
cols = df.columns.tolist()
cols_1st = {"id", "date"}
cols = set(cols) - cols_1st
cols = list(cols_1st) + list(cols)
# wrong column order
df2 = df[cols]
# using lists
cols = df.columns.tolist()
cols_1st = ["id", "date"]
cols = [c for c in cols if c not in cols_1st]
cols = cols_1st + cols
# right column order, but is there a better way?
df3 = df[cols]
The pandas way is more tedious, but I'm fairly new to this. Is there a better way?