Coming from R & Spreadsheets

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Two groups of readers arrive at pandas with strong habits: people who analyse data in R, and people who live in spreadsheets. Both already know what they want to do (filter, summarise, join, reshape); the work is learning the pandas vocabulary and, more importantly, the few places where the model differs. This page gives a translation table for each tool, runs the examples on Python 3.13 with pandas 3.1.0 and NumPy 2.5.4 (checked in October 2026, output shown is real), and states the differences that cause silent wrong answers. It follows the official "Comparison with R / R libraries" and "Comparison with spreadsheets" guides.

If you come from SQL read Coming from SQL; if you are new to pandas, start with 10 Minutes to pandas. The R side of this site is in the R Reference, in particular Data Frames, Factors, Missing and Special Values and Pipes and the Native Pipe. Where R is a better tool than pandas, and the reverse, is discussed in Choosing Tools & Learning Path.

Coming from R

The same idea, a different model

An R data.frame (or tibble) and a pandas DataFrame are both a list of equal-length columns. The differences are in how you address them and what happens at the edges:

Topic R pandas

Indexing base

1-based, ranges include both ends: 1:10 is ten rows

0-based; iloc excludes the end, loc includes it

Column access

df$col, df[["col"]]

df["col"] (a Series), df[["col"]] (a DataFrame)

Row filter

df[cond, ] with a trailing comma

df[cond], df.loc[cond] or df.query("...")

Row names

Optional character labels, rarely used by tidyverse code

A real Index that every operation aligns on and keeps

Missing values

NA of every type, na.rm = TRUE in summaries

NaN in floats, NaT in datetimes, pd.NA in the nullable dtypes; summaries skip missing values by default

Categories

factor

the category dtype

Pipes

%>% or |>

method chaining and .pipe

Copies

Copy-on-modify

Copy-on-Write since pandas 3.0: every derived object behaves as a copy

Non-standard evaluation

filter(df, a > 1) takes bare names

Strings or pd.col("a") expressions; there is no bare-name syntax

Three of these differences deserve a longer explanation.

Zero-based, end-exclusive positions. slice(df, 1:10) and head(df, 10) return ten rows in R; in pandas the same ten rows are df.iloc[:10] or df.head(10). A position slice never includes its end, but a label slice does: df.loc[:, "col1":"col3"] includes col3, which is the behaviour of dplyr’s select(df, col1:col3).

Row labels survive. After df[df["x"] > 1] the surviving rows keep their original labels (for example 2 and 5). That is useful (you can trace a row back) and surprising (positions and labels no longer agree). Call reset_index(drop=True) to renumber.

No bare names. dplyr verbs evaluate a > 1 inside the data frame. pandas evaluates an expression where you write it, so you must name the frame (df["a"] > 1). Two helpers close the gap: df.query(a  1) takes a string and sees the columns as variables, and pandas 3 added column expressions, df.loc[pd.col("a") > 1], which stand for "column a of whichever frame this is applied to" and work inside assign, loc and method chains.

dplyr verbs

The examples use this small frame:

import numpy as np
import pandas as pd

df = pd.DataFrame({
    "col1": [1, 1, 2, 1, 3, 2],
    "col2": [1, 0, 1, 1, 0, 1],
    "col3": [5.0, 6.5, 7.0, 8.5, 9.0, 4.0],
    "col4": list("abcdef"),
})
R (dplyr or base) pandas

dim(df)

df.shape

head(df)

df.head()

slice(df, 1:10)

df.iloc[:10]

filter(df, col1 == 1, col2 == 1)

df.query("col1 == 1 & col2 == 1") or df[(df.col1 == 1) & (df.col2 == 1)]

select(df, col1, col2)

df[["col1", "col2"]]

select(df, col1:col3)

df.loc[:, "col1":"col3"]

select(df, -(col1:col3))

df.drop(columns=cols_to_drop)

distinct(select(df, col1))

df[["col1"]].drop_duplicates()

sample_n(df, 10)

df.sample(n=10)

sample_frac(df, 0.01)

df.sample(frac=0.01)

arrange(df, col1, col2)

df.sort_values(["col1", "col2"])

arrange(df, desc(col1))

df.sort_values("col1", ascending=False)

rename(df, col_one = col1)

df.rename(columns={"col1": "col_one"})

mutate(df, c = a - b)

df.assign(c=df["a"] - df["b"]) or df.assign(c=pd.col("a") - pd.col("b"))

summary(df)

df.describe()

group_by(df, col1)

df.groupby("col1")

summarise(gdf, avg = mean(col1, na.rm = TRUE))

df.groupby("col1").agg(avg=("col1", "mean"))

print(df.query("col1 == 1 & col2 == 1"))
print(df.loc[:, "col1":"col3"].columns.tolist())
print(df.drop(columns=["col1", "col2"]).columns.tolist())
print(df[["col1"]].drop_duplicates())
print(df.sort_values(["col1", "col3"], ascending=[True, False]).index.tolist())
print(df.assign(c=df["col3"] - df["col1"]).head(2))
   col1  col2  col3 col4
0     1     1   5.0    a
3     1     1   8.5    d
['col1', 'col2', 'col3']
['col3', 'col4']
   col1
0     1
2     2
4     3
[3, 1, 0, 2, 5, 4]
   col1  col2  col3 col4    c
0     1     1   5.0    a  4.0
1     1     0   6.5    b  5.5

select(df, -(col1:col3)) has no one-line equivalent when you start from a label range: build the list of names to drop first (cols_to_drop = df.loc[:, "col1":"col3"].columns). The old inplace=True argument of drop is deprecated in pandas 3.1; assign the result instead.

Grouping and summarising

summarise after group_by is groupby followed by agg. Named aggregation, new_name=("column", "function"), is the closest to dplyr’s new_name = fun(column):

print(df.groupby("col1").agg(avg=("col3", "mean"), total=("col3", "sum"), n=("col3", "size")))
print(df.groupby("col1", as_index=False)["col3"].mean())
           avg  total  n
col1
1     6.666667   20.0  3
2     5.500000   11.0  2
3     9.000000    9.0  1
   col1      col3
0     1  6.666667
1     2  5.500000
2     3  9.000000

Compared with dplyr, remember that the group keys become the index of the result (pass as_index=False or call reset_index() to get them back as a column), that rows whose key is NaN are dropped unless you pass dropna=False (R’s aggregate behaves the same way and shows NaN groups as missing), and that sum() on a frame with text columns concatenates the strings instead of failing: pd.DataFrame({"g": [1, 1, 2], "t": ["a", "b", "c"], "v": [1.0, 2.0, 3.0]}) grouped by g gives "ab" for the text column. Select the numeric columns first or pass numeric_only=True.

Base R idioms

Base R pandas

df[, c("a", "c", "e")]

df[["a", "c"]] or df.loc[:, ["a", "c"]]

Non-contiguous column positions

df.iloc[:, np.r_[:10, 24:30]]

x %in% c(2, 4)

s.isin([2, 4])

match(x, table)

no single equivalent; pd.Index(table).get_indexer(x) returns positions

subset(df, a <= b)

df.query("a <= b") or df[df["a"] <= df["b"]]

with(df, a + b)

df.eval("a + b")

aggregate(x, by, mean)

df.groupby(["by1", "by2"])[["v1", "v2"]].mean()

tapply(values, groups, max)

df.pivot_table(values="v", columns="g", aggfunc="max")

print(df["col1"].isin([2, 3]).tolist())
print(df.query("col3 <= 6").shape, df.eval("col1 + col2").tolist())

base = pd.DataFrame({"team": ["a", "a", "b", "b"], "bat": [0.2, 0.3, 0.25, 0.4]})
print(base.pivot_table(values="bat", columns="team", aggfunc="max"))
[False, False, True, False, True, True]
(2, 4) [2, 1, 3, 2, 3, 3]
team    a    b
bat   0.3  0.4

eval and query are convenient, and they only run faster than plain Python above roughly 100,000 rows with several operations in the expression (they need the optional numexpr package for that, installed with pandas[performance]).

plyr and reshape2: split-apply-combine and reshaping

plyr::ddply is groupby plus agg. melt and dcast map to pd.melt and pivot_table; the tidyr verbs pivot_longer and pivot_wider map to the same functions (pd.melt/DataFrame.melt and DataFrame.pivot or pivot_table):

d = pd.DataFrame({"month": [1, 1, 2, 2], "week": [1, 1, 1, 2], "x": [1.0, 2.0, 3.0, 5.0]})
print(d.groupby(["month", "week"])["x"].agg(["mean", "std"]).round(2))

cheese = pd.DataFrame({"first": ["John", "Mary"], "last": ["Doe", "Bo"],
                       "height": [5.5, 6.0], "weight": [130, 150]})
print(pd.melt(cheese, id_vars=["first", "last"]))          # reshape2::melt / tidyr::pivot_longer

feed = pd.DataFrame({"Animal": ["cat", "dog", "cat", "dog"], "FeedType": ["a", "a", "b", "b"],
                     "Amount": [1, 2, 3, 4]})
wide = feed.pivot_table(values="Amount", index="Animal", columns="FeedType", aggfunc="sum")
print(wide)                                                # reshape2::dcast / tidyr::pivot_wider
print(wide.reset_index().columns.tolist())
            mean   std
month week
1     1      1.5  0.71
2     1      3.0   NaN
      2      5.0   NaN
  first last variable  value
0  John  Doe   height    5.5
1  Mary   Bo   height    6.0
2  John  Doe   weight  130.0
3  Mary   Bo   weight  150.0
FeedType  a  b
Animal
cat       1  3
dog       2  4
['Animal', 'a', 'b']

Two details differ from R. A standard deviation of a single value is NaN in pandas (the sample standard deviation is undefined), exactly as in R. And melting columns of different dtypes into one value column produces a common dtype: the integer weight became a float next to the float height. The long format, stack and explode are covered in Melt, Stack & Explode and Pivot & Pivot Tables.

Pipes become method chains

R code reads left to right through %>% or |>. In pandas the same flow is a chain of methods, and a function that is not a method is inserted with pipe:

frame = pd.DataFrame({"g": ["a", "a", "b"], "x": [1, 2, 3], "y": [4, 5, 6]})

result = (
    frame
    .query("x > 1")                                           # filter()
    .assign(z=lambda d: d["x"] * d["y"])                      # mutate()
    .groupby("g", as_index=False)                             # group_by()
    .agg(total=("z", "sum"))                                  # summarise()
    .sort_values("total", ascending=False)                    # arrange(desc())
)
print(result)
   g  total
1  b     18
0  a     10

A frame can also be passed to any function with frame.pipe(func, *args). Prefer a chain over a sequence of reassignments of the same variable and avoid inplace=True, which breaks chains and is deprecated in 3.1. See User-Defined Functions for pipe, apply and agg with your own functions.

Factors and categories

R’s factor is pandas' category dtype; cut is pd.cut:

f = pd.Series([1, 2, 3, 2, 2, 3]).astype("category")
print(f.cat.categories.tolist(), f.cat.codes.tolist())      # levels and integer codes (0-based)

grade = pd.Categorical(["lo", "hi", "lo"], categories=["lo", "hi"], ordered=True)
print(grade, grade.max())                                     # ordered factor: levels in the order you give

print(pd.cut([1, 5, 9], bins=[0, 3, 6, 10], labels=["low", "mid", "high"]).tolist())
[1, 2, 3] [0, 1, 2, 1, 1, 2]
['lo', 'hi', 'lo']
Categories (2, str): ['lo' < 'hi'] hi
['low', 'mid', 'high']

As in R, converting an existing column with astype("category") sorts the levels, while passing categories= keeps exactly the order you give; use cat.reorder_categories to change the order afterwards. Integer codes start at 0 and the missing value has code -1, whereas R’s integer codes start at 1. See Categorical Data for the details.

Missing values

R keeps the type of an NA (NA_integer_, NA_character_), so an integer vector with an NA is still integer. In pandas the default NumPy integer dtype cannot hold a missing value, so a column with a gap is silently converted to float64:

print(pd.Series([1, 2, np.nan]).dtype)                       # float64
print(pd.Series([1, 2, None], dtype="Int64").tolist())        # nullable integer keeps the type
float64
[1, 2, <NA>]

The nullable dtypes (Int64, Float64, boolean and the "string" dtype) use pd.NA and are closer to R’s behaviour, including three-valued logic. Details in Nullable Dtypes and Missing Data.

Coming from spreadsheets

The correspondence

A worksheet and a DataFrame side by side: the whole table, a column as a Series, the index as row headings, one dtype per column and NaN for an empty cell
Figure 1. A worksheet and a DataFrame side by side

In the figure, marker 1 is the whole sheet, a DataFrame; marker 2 is a column, a Series; marker 3 is the row headings, the Index; marker 4 is the data type, which is one per column; marker 5 is an empty cell, NaN.

Spreadsheet pandas

Worksheet

DataFrame

Column

Series

Row headings (1, 2, 3)

Index

Row

a row that keeps its label when rows are sorted or filtered

Empty cell

NaN

The single most important difference is the type of a column. A cell can hold a number, text or a date regardless of its neighbours; a DataFrame column has one dtype, and one text value in a column of numbers makes the whole column object or str. That is why pandas reading a column in which an empty cell appears gives float64 instead of integers (marker 5 turns the integers above into floats). Another is that a pandas expression is vectorised: you write one expression for the whole column instead of dragging a formula down.

Reading, saving and looking at data

Spreadsheet pandas

Open a CSV

pd.read_csv("file.csv")

Text Import Wizard (tab-separated, no header)

pd.read_csv("file.tsv", sep="\t", header=None)

Open an .xlsx file

pd.read_excel("file.xlsx", sheet_name="Sheet1")

Save as .xlsx

df.to_excel("file.xlsx", index=False)

Save as CSV

df.to_csv("file.csv", index=False)

Scroll through rows

df.head(5), df.tail(); large frames print truncated by default

Reading and writing .xlsx needs the openpyxl engine (pip install "pandas[excel]"). A few facts help when you exchange files with colleagues. Formulas are read as the last values Excel saved, never as formulas, and a workbook that was never opened and saved by a spreadsheet program has no saved values. to_excel writes values only: since pandas 3.0 it no longer applies pandas' default header styling. The .xls and .xlsb formats need the xlrd and pyxlsb engines, which are deprecated in pandas 3.1; the python-calamine engine reads them, and .ods too. All of this is detailed in Excel and CSV & Text Files.

Formulas become column expressions

Dragging a formula down a column is a vectorised expression. A new column is just an assignment:

tips = pd.DataFrame({
    "total_bill": [16.99, 10.34, 21.01, 23.68, 24.59, 8.77],
    "tip":        [1.01, 1.66, 3.50, 3.31, 3.61, 2.00],
    "sex":        ["Female", "Male", "Male", "Male", "Female", "Male"],
    "day":        ["Sun", "Sun", "Thur", "Thur", "Sat", "Sat"],
    "size":       [2, 3, 3, 2, 4, 2],
})

tips["half"] = tips["total_bill"] / 2                  # =B2/2, filled down
print(tips["half"].head(2).tolist())
tips = tips.drop(columns="half")                       # delete the column

print(np.where(tips["total_bill"] < 10, "low", "high").tolist())    # =IF(B2<10, "low", "high")
[8.495, 5.17]
['high', 'high', 'high', 'high', 'high', 'low']

Filtering replaces the AutoFilter, and counting the matches replaces the status bar:

print(tips[tips["total_bill"] > 20].shape)             # AutoFilter: total_bill greater than 20
is_sat = tips["day"] == "Sat"
print(is_sat.value_counts().to_dict(), tips[is_sat].shape)
print(tips["tip"].sum(), tips["tip"].mean().round(3), tips["tip"].count(), tips["tip"].max())   # SUM, AVERAGE, COUNT, MAX
print(tips["tip"].rank().tolist())                     # RANK
(3, 5)
{False: 4, True: 2} (2, 5)
15.09 2.515 6 3.61
[1.0, 2.0, 5.0, 4.0, 6.0, 3.0]
Excel pandas

=SUM(B2:B7), =AVERAGE(), =MIN(), =MAX()

df["col"].sum(), .mean(), .min(), .max()

=COUNT(B2:B7)

df["col"].count() (non-missing values)

=IF(B2 < 10, "low", "high")

np.where(cond, "low", "high"); several branches with np.select

=IFERROR(...), =ISBLANK()

fillna, isna

=ROUND(B2, 1)

df["col"].round(1)

Sort dialog (sex, then total_bill)

tips.sort_values(["sex", "total_bill"])

Hide or reorder columns

tips[["sex", "total_bill", "tip"]]

Delete a column

tips.drop(columns="sex")

Rename a header cell

tips.rename(columns={"total_bill": "bill"})

Remove Duplicates

df.drop_duplicates() or df.drop_duplicates(["class", "student_count"])

Fill handle

assign a list to a slice: df.loc[2:5, "AAA"] = [1, 2, 3, 4]

Add a row at the bottom

pd.concat([df, new_row_frame], ignore_index=True)

Dates

A spreadsheet parses dates as you type, and a date is a number with a format. pandas parses on request (pd.to_datetime or the parse_dates argument of read_csv), and then offers the .dt accessor:

Excel pandas

=YEAR(A2), =MONTH(A2), =DAY(A2)

s.dt.year, s.dt.month, s.dt.day

=TEXT(A2, "dd mmm yyyy")

s.dt.strftime("%d %b %Y")

=WEEKDAY(A2)

s.dt.day_name() or s.dt.dayofweek (Monday is 0)

=DATE(YEAR(A2), MONTH(A2) + 1, 1)

s + pd.offsets.MonthBegin()

=B2 - A2 (days)

(end - start).dt.days

=DATEDIF(A2, B2, "M")

end.dt.to_period("M") - start.dt.to_period("M")

dd = pd.DataFrame({"start": pd.to_datetime(["2013-01-15", "2013-02-20"]),
                   "end":   pd.to_datetime(["2013-04-10", "2013-02-28"])})

print((dd["start"] + pd.offsets.MonthBegin()).dt.strftime("%Y-%m-%d").tolist())
print((dd["end"] - dd["start"]).dt.days.tolist())
months = dd["end"].dt.to_period("M") - dd["start"].dt.to_period("M")
print(months.tolist(), months.map(lambda off: off.n).tolist())     # month offsets, then plain integers
print(pd.to_datetime(pd.Series(["03/04/2013"]), format="%d/%m/%Y").dt.month.tolist())   # explicit format
['2013-02-01', '2013-03-01']
[85, 8]
[<3 * MonthEnds>, <0 * MonthEnds>] [3, 0]
[4]

Always pass format= (or dayfirst) for ambiguous text dates, because a spreadsheet silently uses the machine’s locale, and pandas 3 defaults to microsecond resolution for datetimes (datetime64[us]), not nanoseconds. The difference of two periods is a month offset object; its .n attribute is the integer. Keep dates as datetimes during calculations and format them only for output. Time zones use zoneinfo. More in Time Series.

Text functions

Excel pandas

=LEN(TRIM(A2))

s.str.strip().str.len()

=FIND("ob", A2) (1-based, error if absent)

s.str.find("ob") (0-based, -1 if absent)

=MID(A2, 1, 1), =LEFT(A2, 1)

s.str[0:1]

Text to Columns

s.str.split(" ", expand=True)

=UPPER(), =LOWER(), =PROPER()

s.str.upper(), s.str.lower(), s.str.title()

=SUBSTITUTE(A2, "a", "b")

s.str.replace("a", "b", regex=False)

Find (highlight cells)

boolean mask: s.str.contains("S")

s = pd.Series(["  Alessandra ", "Bob Smith", "Carl"])
print(s.str.strip().str.len().tolist(), s.str.find("ob").tolist(), s.str[0:1].tolist())
print(s.str.strip().str.split(" ", expand=True))
print(s.str.strip().str.title().tolist())
[10, 9, 4] [-1, 1, -1] [' ', 'B', 'C']
            0      1
0  Alessandra    NaN
1         Bob  Smith
2        Carl    NaN
['Alessandra', 'Bob Smith', 'Carl']

Because the column has the str dtype, .str methods return missing values for missing input and never fail on them. The pandas 3 str.replace is literal by default (regex=False); older code that relied on a regular expression must now say regex=True. Details in Text Data & the str Dtype.

VLOOKUP becomes merge

VLOOKUP finds a key in the first column of a range and returns another column. merge does the same for every row at once and is much more general: the key need not be the first column, no sorting is required, several columns can come back, and every match gets a row.

prices = pd.DataFrame({"key": ["a", "b", "c"], "price": [1, 2, 3]})
items = pd.DataFrame({"key": ["b", "a", "z", "a"], "qty": [5, 6, 7, 8]})
print(items.merge(prices, on="key", how="left"))      # =VLOOKUP(A2, prices, 2, FALSE)
  key  qty  price
0   b    5    2.0
1   a    6    1.0
2   z    7    NaN
3   a    8    1.0

The unmatched key z yields NaN, the counterpart of #N/A. Use how="inner" to drop unmatched rows. Add validate="many_to_one" so that an accidental duplicate key in the lookup table raises an error instead of duplicating rows silently. See Merge & Join.

Pivot tables

A PivotTable is pivot_table (or groupby with unstack). Pass margins=True for the "Grand Total" row and column:

print(pd.pivot_table(tips, values="tip", index="size", columns="sex", aggfunc="mean", margins=True).round(2))
sex   Female  Male   All
size
2       1.01  2.66  2.11
3        NaN  2.58  2.58
4       3.61   NaN  3.61
All     2.31  2.62  2.52

The aggfunc can be a name ("mean", "sum", "count"), a function or a list. The default is "mean". Because a pivot table is a regular DataFrame, you can keep going with reset_index(), formulas on the result and charts. More in Pivot & Pivot Tables.

Find and replace, and one trap

Find and Replace All is replace (whole cell values) or .str.replace (parts of a text):

print(tips.replace("Thur", "Thursday")["day"].tolist())                # whole value matches
print(tips.replace("Thu", "Thursday")["day"].tolist())                 # no cell equals "Thu": nothing changes
print(tips["day"].str.replace("Thu", "Thursday", regex=False).tolist())   # substring match
['Sun', 'Sun', 'Thursday', 'Thursday', 'Sat', 'Sat']
['Sun', 'Sun', 'Thur', 'Thur', 'Sat', 'Sat']
['Sun', 'Sun', 'Thursdayr', 'Thursdayr', 'Sat', 'Sat']

The trap is in the last two lines. DataFrame.replace matches the entire cell, so "Thu" replaces nothing when the data contains "Thur"; and the substring version replaces the first three letters of "Thur" and leaves the trailing r. Neither raises an error. Check the result with value_counts().

Limits and what spreadsheets do better

pandas is not a spreadsheet. There is no live recalculation: change a value and nothing downstream updates until you rerun the code, which is a feature when you want a reproducible analysis and a drawback for ad-hoc what-if modelling. There is no cell formatting, formulas or charts embedded in the file you write. In exchange you get a script that anyone can rerun, no row limit other than memory (an Excel sheet stops at 1,048,576 rows), version control, tests and a clear separation between data and logic. For tables far beyond memory see Scaling to Large Datasets and Beyond the Core: Polars, Arrow, DuckDB & Deep Learning.

Where older guides and tutorials are outdated

Older statement pandas 3.1

df.ix[...] mixes label and position indexing

.ix was removed in pandas 1.0; use loc and iloc.

df.append(row) adds a row

Removed in 2.0; use pd.concat once on a list of pieces.

df.applymap(f) applies to every cell

Removed in 3.0; use DataFrame.map.

pd.value_counts(x)

Removed in 3.0; call x.value_counts().

df["a"][mask] = 1

Chained assignment never works with Copy-on-Write; use df.loc[mask, "a"] = 1.

fillna(method="ffill")

Removed in 3.0; use ffill() and bfill().

freq="M", "H", "T"

Removed in 3.0: use "ME", "h", "min".

The official R page says slice(df, 1:10) is df.iloc[:9]

Ten rows are df.iloc[:10]; position slices exclude the end.

inplace=True everywhere

Deprecated in pandas 3.1 for the most common methods.