Q&A 17 How do you drop or reorder columns in Python and R?

17.1 Explanation

Sometimes you want to exclude a column or rearrange the order of columns for reporting or modeling. This improves readability and usability.


17.2 Python Code

import pandas as pd

# Load dataset
df = pd.read_csv("data/iris.csv")

# Drop petal_width column
df_dropped = df.drop(columns=["petal_width"])

# Reorder columns
cols = ["species", "sepal_length", "sepal_width", "petal_length"]
df_reordered = df[cols]

print(df_reordered.head())
  species  sepal_length  sepal_width  petal_length
0  setosa           5.1          3.5           1.4
1  setosa           4.9          3.0           1.4
2  setosa           4.7          3.2           1.3
3  setosa           4.6          3.1           1.5
4  setosa           5.0          3.6           1.4

17.3 R Code

library(readr)
library(dplyr)

# Load dataset
df <- read_csv("data/iris.csv")

# Drop petal_width column
df_dropped <- df %>%
  select(-petal_width)

# Reorder columns
df_reordered <- df %>%
  select(species, sepal_length, sepal_width, petal_length)

head(df_reordered)
# A tibble: 6 × 4
  species sepal_length sepal_width petal_length
  <chr>          <dbl>       <dbl>        <dbl>
1 setosa           5.1         3.5          1.4
2 setosa           4.9         3            1.4
3 setosa           4.7         3.2          1.3
4 setosa           4.6         3.1          1.5
5 setosa           5           3.6          1.4
6 setosa           5.4         3.9          1.7

✅ Dropping and reordering columns gives you control over which features to keep and how to present them.