Python for Excel users · Lesson 5 of 14

Excel formulas as pandas column calculations

Turn fill-down formulas, absolute references, ROUND, running totals and row sums into one-line pandas column calculations.

About 15 minutes · code runs in your browser, nothing to install

In Excel you type =B2*C2 in D2 and drag the fill handle down to the last row. In pandas you write the calculation once for the whole column. There is no fill handle, no gaps where someone forgot to drag, and the formula works for 10 rows or 10 million.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "Item": ["Lamp", "Chair", "Desk", "Rug", "Shelf"],
    "Units": [4, 2, 1, 3, 5],
    "Price": [19.99, 45.0, 120.0, 34.5, 27.25],
})
df["Total"] = df["Units"] * df["Price"]
print(df)
Output
    Item  Units   Price   Total
0   Lamp      4   19.99   79.96
1  Chair      2   45.00   90.00
2   Desk      1  120.00  120.00
3    Rug      3   34.50  103.50
4  Shelf      5   27.25  136.25

df["Total"] = … creates a new column, like typing a header in an empty column and filling the formula down.

Absolute references: $F$1 becomes a variable

In Excel you might keep the VAT rate in F1 and write =D2*(1+$F$1) so that the reference does not move when you fill down. In Python the rate is just a variable. A single number is used for every row automatically.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "Item": ["Lamp", "Chair", "Desk", "Rug", "Shelf"],
    "Units": [4, 2, 1, 3, 5],
    "Price": [19.99, 45.0, 120.0, 34.5, 27.25],
})
vat = 0.21
df["Total"] = df["Units"] * df["Price"]
df["With VAT"] = (df["Total"] * (1 + vat)).round(2)
print(df[["Item", "Total", "With VAT"]])
Output
    Item   Total  With VAT
0   Lamp   79.96     96.75
1  Chair   90.00    108.90
2   Desk  120.00    145.20
3    Rug  103.50    125.24
4  Shelf  136.25    164.86

.round(2) is =ROUND(…, 2) for a whole column.

ROUND, ROUNDUP and ROUNDDOWN

.round(n) rounds to n decimals. For =ROUNDUP(x, 0) and =ROUNDDOWN(x, 0) use NumPy's np.ceil and np.floor, which round up or down to a whole number. They match Excel for positive numbers; for negative ones Excel rounds away from or towards zero, so ROUNDDOWN(-2.5, 0) is -2 while np.floor(-2.5) is -3 (np.trunc matches ROUNDDOWN there).

Pythoneditable
import numpy as np
import pandas as pd

boxes = pd.Series([2.1, 3.0, 4.75])
print(np.ceil(boxes).tolist())
print(np.floor(boxes).tolist())
Output
[3.0, 3.0, 5.0]
[2.0, 3.0, 4.0]

=ROUNDUP(2.1, 0) is 3: handy for "how many boxes do I need".

Watch out: pandas and Python round an exact half to the nearest even number, so 0.5 becomes 0 and 2.5 becomes 2, while Excel's ROUND gives 1 and 3. For money that must match Excel to the cent, round with Python's decimal module as shown below.
Pythoneditable
from decimal import Decimal, ROUND_HALF_UP
import pandas as pd

s = pd.Series([0.5, 2.5, 2.675])
print(s.round().tolist())

def excel_round(x, places=2):
    q = Decimal(1).scaleb(-places)
    d = Decimal(str(x)).quantize(q, rounding=ROUND_HALF_UP)
    return float(d)

print(s.map(lambda x: excel_round(x, 0)).tolist())
print(excel_round(2.675))
Output
[0.0, 2.0, 3.0]
[1.0, 3.0, 3.0]
2.68

excel_round turns each number into an exact decimal first, then rounds halves up the way Excel does.

Running totals and percent of total

A running total in Excel is =SUM($D$2:D2) filled down. In pandas it is .cumsum(). A share of the total, =D2/SUM($D$2:$D$6), is the column divided by its sum.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "Item": ["Lamp", "Chair", "Desk", "Rug", "Shelf"],
    "Units": [4, 2, 1, 3, 5],
    "Price": [19.99, 45.0, 120.0, 34.5, 27.25],
})
df["Total"] = df["Units"] * df["Price"]
df["Running"] = df["Total"].cumsum()
df["Share %"] = (df["Total"] / df["Total"].sum() * 100).round(1)
print(df[["Item", "Total", "Running", "Share %"]])
Output
    Item   Total  Running  Share %
0   Lamp   79.96    79.96     15.1
1  Chair   90.00   169.96     17.0
2   Desk  120.00   289.96     22.7
3    Rug  103.50   393.46     19.5
4  Shelf  136.25   529.71     25.7

Sums across a row

=SUM(B2:D2) adds cells across a row. In pandas pick the columns and add axis=1, which means "across". Without it, .sum() adds down each column.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "Rep": ["Ana", "Ben", "Chloe"],
    "Jan": [1200, 950, 1400],
    "Feb": [1100, 1020, 1380],
    "Mar": [1300, 990, 1500],
})
df["Q1"] = df[["Jan", "Feb", "Mar"]].sum(axis=1)
df["Avg"] = df[["Jan", "Feb", "Mar"]].mean(axis=1).round(0)
print(df)
Output
     Rep   Jan   Feb   Mar    Q1     Avg
0    Ana  1200  1100  1300  3600  1200.0
1    Ben   950  1020   990  2960   987.0
2  Chloe  1400  1380  1500  4280  1427.0

✎ Exercise

Add a column Net that is Price minus the discount (Price * Discount), and a column Gross that adds 20% VAT to Net, rounded to 2 decimals. Print the table.

Hint: Write each formula once for the whole column; vat is a normal variable, like an absolute reference.

Your codewrite your answer, then Run
import pandas as pd

df = pd.DataFrame({
    "Item": ["Pen", "Pad", "Ink"],
    "Price": [2.5, 8.0, 15.0],
    "Discount": [0.0, 0.1, 0.2],
})
vat = 0.20
# your code here

Expected output:

  Item  Price  Discount   Net  Gross
0  Pen    2.5       0.0   2.5   3.00
1  Pad    8.0       0.1   7.2   8.64
2  Ink   15.0       0.2  12.0  14.40
Show a solution
Solutioneditable
import pandas as pd

df = pd.DataFrame({
    "Item": ["Pen", "Pad", "Ink"],
    "Price": [2.5, 8.0, 15.0],
    "Discount": [0.0, 0.1, 0.2],
})
vat = 0.20
df["Net"] = df["Price"] - df["Price"] * df["Discount"]
df["Gross"] = (df["Net"] * (1 + vat)).round(2)
print(df)
Output
  Item  Price  Discount   Net  Gross
0  Pen    2.5       0.0   2.5   3.00
1  Pad    8.0       0.1   7.2   8.64
2  Ink   15.0       0.2  12.0  14.40

Check yourself

1. How do you "fill down" =B2*C2 for every row in pandas?

2. What replaces an absolute reference like $F$1 holding a tax rate?

3. What does pd.Series([2.5]).round() give?

Spotted a mistake on this page? Tell us