Build a table from a dictionary of lists, select columns from it, add a computed column, sort it, and filter its rows.
A DataFrame is a table: several Series stacked side by side, all sharing one index. Row 2 means the same row in every column, so a ticker, its price and its share count stay together.
In this lesson I build a holdings table from a dictionary of lists, add a position value, and turn those values into portfolio weights.
Step 1. A table from a dictionary of lists
Each key becomes a column name and each list becomes that column. The lists must be the same length, because they line up row by row. The smallest table that works is two keys and two short lists.
The same call builds a holdings table, with a text column and two number columns.
df = pd.DataFrame({ # one dictionary in, one table out"Ticker": ["AAA", "CCC", "DDD", "EEE"], # each key is a column name"Close": [185.40, 410.20, 130.75, 178.30], # each list is one column"Shares": [10, 5, 20, 8], # a third list, same length again})print(df)# -> Ticker Close Shares# -> 0 AAA 185.40 10# -> 1 CCC 410.20 5# -> 2 DDD 130.75 20# -> 3 EEE 178.30 8
Every column carries one type, and .dtypes lists them.
print(df.dtypes) # one type per column, in column order# -> Ticker object# -> Close float64# -> Shares int64# -> dtype: object
Ticker object
Close float64
Shares int64
dtype: object
Ticker holds text, which pandas reports as object. Close holds decimals, float64. Shares holds whole numbers, int64.
Step 3. One column is a Series, two columns are a DataFrame
Square brackets with one name hand back that column on its own. That is a Series, the object from Lesson 14, and it carries the same index as the table it came from.
close = df["Close"] # one name hands back that column aloneprint(type(close)) # -> <class 'pandas.core.series.Series'>print(close)# -> 0 185.40# -> 1 410.20# -> 2 130.75# -> 3 178.30# -> Name: Close, dtype: float64
DDD is the cheapest share here and the largest weight, at 32.9% of the portfolio.
Your turn
Using the table from Step 6, print the ticker and weight of every holding under 25% of the portfolio, and print how many rows that leaves.
TipShow answer
small = df[df["Weight"] <0.25] # rows under 25% of the portfolioprint(small[["Ticker", "Weight"]])# -> Ticker Weight# -> 0 AAA 0.233313# -> 3 EEE 0.179503print(small.shape) # -> (2, 5) <- 2 rows, still all 5 columns
NotePairing by label, not by position
df["Close"] * df["Shares"] does not pair the two columns by position. It pairs them by index label, then multiplies. Both columns come from the same table, so the labels are identical and the result is what you expect.
Two Series from different tables can carry different labels, and pandas will still align them by label rather than by position. Lesson 24 covers what happens when the labels do not match.