How do I summarise a long table with pivot_table and crosstab?
Sum fund holdings by sector with pivot_table, count holdings with crosstab, and compare a sector’s share by number of holdings with its share by invested value.
After this lesson, you can turn a long table of fund holdings into one column per sector and compare a sector’s share by number of holdings with its share by invested value.
How do I sum the holdings by sector?
holdings.pivot_table(values="market_value", index=["month", "fund"], columns="sector", aggfunc="sum") adds the market values of each month, fund and sector into one cell, one row per month and fund and one column per sector. F1’s two January Tech holdings, 30 and 20 million SEK, give 50.
The made-up holdings table has one row per fund, company and month, with market values in millions of SEK. Without aggfunc="sum", the cell gets the default mean, 25. .pivot() needs one row per cell, so the two January Tech rows of F1 make it raise a ValueError. The same calculations compare the sector mix of emerging-markets funds.
The following box builds the holdings, sums them by sector and tries .pivot().
sector Banks Tech
month fund
2026-01 F1 50 50
F2 40 60
2026-02 F1 60 40
F2 75 25
ValueError
How do I count the holdings?
pd.crosstab(january["fund"], january["sector"]) counts the rows of each fund and sector, and normalize="index" divides each count by its row’s total. F1 has three January holdings, two in Tech, so its Tech share by number is 2 / 3 = 0.67.
normalize="columns" divides by each column’s total and normalize="all" by the table’s total.
The following box counts the January holdings and their shares within each fund.
january = holdings[holdings["month"] =="2026-01"]print(pd.crosstab(january["fund"], january["sector"]))print(pd.crosstab(january["fund"], january["sector"], normalize="index").round(2))
sector Banks Tech
fund
F1 1 2
F2 1 1
sector Banks Tech
fund
F1 0.33 0.67
F2 0.50 0.50
How do I get each sector’s share of invested value?
Dividing each sector’s value by the fund’s total value, sector_values.div(sector_values.sum(axis=1), axis="index"), gives the share of the money in each sector. F1’s Tech share by value is 50 / 100 = 0.50, below its share of 0.67 by number, and F2’s is 0.60, above its share of 0.50 by number.
.div(..., axis="index") matches each row total to its row, as in the lesson on aligned arithmetic. The shares cover only the holdings in the table, so cash that is missing from it is missing from the total too.