Skip to content

Data frames in pandas and dplyr

Filter, add columns, group and join in both languages, and let a recipe write the translation for you.

Introductory ~9 min8 steps

What runs in CodeSplash

You will be able to

  • Translate filter, select, mutate, group and join between pandas and dplyr
  • Predict how each language orders and labels a grouped result
  • Use a Prepare recipe's Code tab as a translation

Read first

01

Six verbs

Read

Almost all data wrangling is six verbs. Once you know them in one language, the other is a lookup.

Python
import pandas as pd

df = pd.read_csv("penguins.csv")

(df
 .query("species == 'Gentoo'")                 # filter rows
 [["sex", "body_mass"]]                        # select columns
 .assign(mass_kg=lambda d: d.body_mass / 1000) # add a column
 .sort_values("mass_kg", ascending=False)      # sort
 .groupby("sex", dropna=False)                 # group
 .agg(n=("mass_kg", "size"),                   # summarize
      mean_kg=("mass_kg", "mean"))
)
R
library(dplyr)

df <- read.csv("penguins.csv")

df |>
  filter(species == "Gentoo") |>     # filter rows
  select(sex, body_mass) |>          # select columns
  mutate(mass_kg = body_mass / 1000) |> # add a column
  arrange(desc(mass_kg)) |>          # sort
  group_by(sex) |>                   # group
  summarise(n = n(),                 # summarize
            mean_kg = mean(mass_kg, na.rm = TRUE))

Read them line by line. They do the same thing in the same order.

02

What happens to the missing group?

Predict

Predict first

Some penguins have no recorded sex. By default, does groupby("sex") in pandas and group_by(sex) in dplyr keep a row for them?

Both keep a row for missing sexBoth drop itThey differ unless you say
Reveal

They differ. dplyr keeps a group for NA. pandas drops it unless you pass dropna=False, so the group, and those birds' rows, disappear from your summary without a word. That's why the code above sets it. Check your row counts after any grouping.

03

Try one

In the app

Add the penguins sample, then open a notebook in your stronger language. Load the data and run the six-verb pipeline.

Python
import codesplash as cs

df = cs.table("Palmer penguins (sample)").df()
df.groupby("species", dropna=False)["body_mass"].mean()
R
library(codesplashr)
library(dplyr)

cs_table("Palmer penguins (sample)") |>
  group_by(species) |>
  summarise(mean_mass = mean(body_mass, na.rm = TRUE))
Palmer penguins

Now change the grouping column to island.

04

Joins

Explore

Joins match in both languages, as long as you say which kind. Note the default: pandas merge is an inner join unless you say otherwise, and dplyr names the kind in the function.

Python
# keeps only rows with a match on both sides
df.merge(islands, on="island")

# keeps every penguin, with empty cells for no match
df.merge(islands, on="island", how="left")
R
# keeps only rows with a match on both sides
inner_join(df, islands, by = "island")

# keeps every penguin, with NA for no match
left_join(df, islands, by = "island")

Change a left to an inner in your notebook, and compare row counts before and after. A join that changes your row count unexpectedly deserves a look before you trust anything computed after it.

05

Let a recipe translate

In the app

You don't have to translate by hand. In Prepare, any recipeRecipeAn ordered list of data-preparation steps that replays on new versions and exports to SQL, pandas and dplyr. has a Code view with pandas and dplyr tabs, and the app tests that these exports produce the same output as its own SQL.

Build a two-step recipe, such as a filter and a new column, and read it in both. A recipe you already understand is a good way to learn the other language.

Summaries like these lead naturally to a table with intervals:

06

Check your understanding

Checkpoint

Check yourself

What's the dplyr equivalent of pandas assign?

Show the answer

Answer: b

assign and mutate add or change columns and keep every row. summarise collapses rows.

Check yourself

df.merge(other, on="key") with no how=: what do you get?

Show the answer

Answer: a

pandas defaults to inner. Rows without a match vanish. If you meant to keep them, say how="left", the same way you'd choose left_join in dplyr.

Check yourself

After a groupby, your counts add up to fewer rows than the data has. What's the likeliest cause in pandas?

Show the answer

Answer: b

Adding dropna=False keeps them as their own group. Comparing totals is a two-second check that catches this.

07

Which verb do you forget?

Reflect

Which of the six verbs do you find hardest in your less familiar language? Write that one line on a card. A small lookup you made yourself sticks better than a cheat sheet you downloaded.

08

Recap

Recap
  • Six verbs cover most wrangling, and they translate directly.
  • pandas drops missing groups by default and dplyr keeps them.
  • A recipe's Code view shows the same steps in pandas and dplyr.

Concepts in this lesson