Part 3 · Working with the data · 2 of 6
Python & pandas 101: the formulas
Lists, dicts, and the DataFrame moves that mirror SQL: select, filter, group, sort, merge.
1 min read
Python in one breath
x = 5 # variable
stages = ['qualified', 'proposal'] # list; stages[0], len(stages)
deal = {'id': 'D-1', 'amount': 5000} # dict; deal['amount']
round(2 / 3, 4) # 0.6667
[s for s in stages if s != 'proposal'] # list comprehension (a filter)
== compares, = assigns. // is integer division. Indentation defines
blocks.
pandas ↔ SQL
| SQL | pandas |
|---|---|
SELECT deal_id, amount FROM deals | deals[['deal_id', 'amount']] |
WHERE stage = 'closed_won' | deals[deals['stage'] == 'closed_won'] |
WHERE a AND b | deals[(cond_a) & (cond_b)] — parentheses required |
WHERE stage IN (...) | deals[deals['stage'].isin([...])] |
COUNT(*) | len(deals) |
SUM(amount) | deals['amount'].sum() |
GROUP BY owner, SUM(amount) | deals.groupby('owner')['amount'].sum() |
ORDER BY amount DESC | .sort_values('amount', ascending=False) |
LIMIT 5 | .head(5) |
JOIN accounts ON account_id | deals.merge(accounts, on='account_id') |
LEFT JOIN | .merge(..., how='left') |
| several aggregates | .agg(total=('amount', 'sum'), n=('deal_id', 'count')) |
Getting an answer out
result = df.to_dict('records') for rows; int(x) / float(x) to turn a
numpy number into a plain one; (deals['stage'] == 'closed_won').sum()
counts True values, the pandas CASE WHEN.
Source: Synthesized for DPM Lab (Level 0).
Where this shows up