Data analysis with pandas · Lesson 7 of 15

New columns and calculations

Add columns calculated from other columns, use NumPy arrays and np.where for fast maths and choices, and build running totals and shares.

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

Most analysis means calculating something new from what you have: a total from quantity and price, VAT, a discount, a share of the whole. In pandas you write the formula once for the whole column, as with a Series in Series: one column of data.

A column from other columns

Assign to a new column name and pandas fills every row. Calculations between columns are done row by row: the first quantity times the first price, and so on.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "item": ["mug", "plate", "bowl", "vase", "jug"],
    "qty": [4, 10, 6, 1, 3],
    "price": [8.50, 6.00, 5.25, 24.00, 12.75],
})

df["total"] = df["qty"] * df["price"]
df["with_vat"] = (df["total"] * 1.20).round(2)
print(df)
print("Sales:", df["total"].sum())
Output
    item  qty  price  total  with_vat
0    mug    4   8.50  34.00      40.8
1  plate   10   6.00  60.00      72.0
2   bowl    6   5.25  31.50      37.8
3   vase    1  24.00  24.00      28.8
4    jug    3  12.75  38.25      45.9
Sales: 187.75

A short look at NumPy

Under the hood pandas stores columns as NumPy arrays. NumPy (imported as np) is the library for fast maths on lists of numbers. An array looks like a list, but +, * and functions work on every element at once.

Pythoneditable
import numpy as np

prices = np.array([2.5, 4.0, 1.2, 3.0])
print(prices * 2)
print(prices + np.array([1, 1, 1, 1]))
print(np.round(np.sqrt(prices), 2))
print("Average:", float(prices.mean()))
Output
[5.  8.  2.4 6. ]
[3.5 5.  2.2 4. ]
[1.58 2.   1.1  1.73]
Average: 2.675

A Python list would repeat itself with * 2; an array doubles each number.

NumPy's np.where(condition, if_true, if_false) picks one of two values for every row. It is the column version of an if/else, like a spreadsheet IF.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "item": ["mug", "plate", "bowl", "vase", "jug"],
    "qty": [4, 10, 6, 1, 3],
    "price": [8.50, 6.00, 5.25, 24.00, 12.75],
})
import numpy as np

df["size"] = np.where(df["qty"] >= 5, "big", "small")
df["discount"] = np.where(df["qty"] >= 5, 0.10, 0.0)
df["pay"] = (df["qty"] * df["price"] * (1 - df["discount"])).round(2)
print(df[["item", "size", "pay"]])
Output
    item   size    pay
0    mug  small  34.00
1  plate    big  54.00
2   bowl    big  28.35
3   vase  small  24.00
4    jug  small  38.25

Your own function with map

For a rule with more than two outcomes, write a normal function and use map on the column: it calls the function once per value. This is slower than column maths, so keep it for things maths cannot do.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "item": ["mug", "plate", "bowl", "vase", "jug"],
    "qty": [4, 10, 6, 1, 3],
    "price": [8.50, 6.00, 5.25, 24.00, 12.75],
})

def band(price):
    if price < 6:
        return "cheap"
    elif price < 15:
        return "mid"
    return "dear"

df["band"] = df["price"].map(band)
print(df[["item", "price", "band"]])
Output
    item  price   band
0    mug   8.50    mid
1  plate   6.00    mid
2   bowl   5.25  cheap
3   vase  24.00   dear
4    jug  12.75    mid

Running totals and shares

cumsum() adds up as it goes down the column, div with the total gives each row's share, and assign lets you add several columns in one step and returns a new DataFrame.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "item": ["mug", "plate", "bowl", "vase", "jug"],
    "qty": [4, 10, 6, 1, 3],
    "price": [8.50, 6.00, 5.25, 24.00, 12.75],
})

df["total"] = df["qty"] * df["price"]
out = df.assign(
    running=df["total"].cumsum(),
    share=(df["total"] / df["total"].sum() * 100).round(1),
)
print(out[["item", "total", "running", "share"]])
Output
    item  total  running  share
0    mug  34.00    34.00   18.1
1  plate  60.00    94.00   32.0
2   bowl  31.50   125.50   16.8
3   vase  24.00   149.50   12.8
4    jug  38.25   187.75   20.4
Tip: Changing a column name or deleting one: df.rename(columns={"qty": "quantity"}) and df.drop(columns=["size"]). Both return a new DataFrame.

✎ Exercise

Add a column total (qty × price) and a column label that says "high" when the total is at least 50 and "low" otherwise. Print item, total and label.

Hint: df["qty"] * df["price"] for the total, then np.where(df["total"] >= 50, "high", "low").

Your codewrite your answer, then Run
import pandas as pd

df = pd.DataFrame({
    "item": ["mug", "plate", "bowl", "vase", "jug"],
    "qty": [4, 10, 6, 1, 3],
    "price": [8.50, 6.00, 5.25, 24.00, 12.75],
})
import numpy as np

# your code here

Expected output:

    item  total label
0    mug  34.00   low
1  plate  60.00  high
2   bowl  31.50   low
3   vase  24.00   low
4    jug  38.25   low
Show a solution
Solutioneditable
import pandas as pd

df = pd.DataFrame({
    "item": ["mug", "plate", "bowl", "vase", "jug"],
    "qty": [4, 10, 6, 1, 3],
    "price": [8.50, 6.00, 5.25, 24.00, 12.75],
})
import numpy as np

df["total"] = df["qty"] * df["price"]
df["label"] = np.where(df["total"] >= 50, "high", "low")
print(df[["item", "total", "label"]])
Output
    item  total label
0    mug  34.00   low
1  plate  60.00  high
2   bowl  31.50   low
3   vase  24.00   low
4    jug  38.25   low

Check yourself

1. What does df["a"] * df["b"] calculate?

2. What does np.where(df["qty"] > 5, "yes", "no") return?

3. What is cumsum() of the values 2, 3, 5?

Spotted a mistake on this page? Tell us