Sales Data Analysis
You have an order export with a few problems in it and you want one number per region: total revenue and order count. This walkthrough cleans the six-row sample, collapses it to three rows with Group By Aggregate, and exports the flow as a pandas or polars script.
You'll use: File Input → Drop Columns → Change Types → Drop Nulls → Filter Rows → Replace Values (twice) → Fill Nulls → Group By Aggregate → Rename Columns → Sort Rows → File Output.
- InputFile Inputsales.csv
- CleanDrop Columnsinternal_note
- CleanChange Typesamount →
float · ordered_at → datetime - CleanDrop Nullssubset: amount
- CleanFilter Rowsamount > 0 (drops refunds)
- CleanReplace Valuesregion: north →
North, south → South - CleanFill Nullsregion →
Unknown - TransformGroup By Aggregateregion · sum(amount) · count(order_id)
- CleanRename Columnsamount →
total_sales · order_id → num_orders - CleanSort Rowstotal_sales, descending
- OutputFile Outputsales_summary.csv
Sample data
Save this as sales.csv, or download sales.csv,
and upload it on the Datasets page:
order_id,region,amount,ordered_at,internal_note
1001,North,120.50,2024-01-03,batch-a
1002,south,89.00,2024-01-03,batch-a
1003,North,,2024-01-04,batch-b
1004,South,-5.00,2024-01-04,refund
1005,,42.25,2024-01-05,batch-b
1006,north,210.00,2024-01-06,batch-cFive things need fixing before the numbers are trustworthy:
internal_noteis an internal column that should not reach the summary.- Order 1003 has no amount.
- Order 1004 is a refund (
-5.00), not revenue. - Order 1005 has no region.
northandsouthare lowercase, so they would form their own groups.
Build the flow
- File Input: set File type to CSV and pick the
sales.csvdataset. - Drop Columns: Columns to drop =
internal_note. - Change Types: under Casts, set
amount→floatandordered_at→datetime. Leave On bad values at Raise an error so a malformed amount stops the run instead of silently turning into null. - Drop Nulls: Subset =
amount. This removes order 1003. Limit the subset toamount, or the row with no region would be dropped too. - Filter Rows: Column
amount, Operator > greater than, Value0. The node keeps the rows where the condition is true, so the refund, order 1004, is dropped. - Replace Values: Column
region, Replacenorth, WithNorth. Add a second Replace Values node forsouth→South. Replace Values matches the whole cell exactly, so each spelling needs its own node. - Fill Nulls: Strategy Constant value, Fill value
Unknown, Columnsregion. Order 1005 keeps its revenue under an explicitUnknowngroup. - Group By Aggregate: Group by columns =
region. Under Aggregations, setamount→sumandorder_id→count. - Rename Columns:
amount→total_sales,order_id→num_orders. After the group-by, those columns hold a sum and a count, so the old names would mislead. - Sort Rows: Sort by columns
total_sales, Order Descending. - File Output: File type CSV, Dataset name
sales_summary.
Select a node to see the live preview of its output, then click Run.
Prefer to describe it?
With a provider key set up, upload the sample data, open a blank flow in the same project and ask the Flow assistant, for example: "Drop internal_note, remove rows with no amount and refunds (amount of 0 or less), lowercase region and fill a missing region with Unknown, then total amount and count order_id per region, largest total first." Review the proposed nodes and settings, then choose Apply and save. We ran this prompt on the sample data; see what the assistant built. Its flow can differ from the steps above in node order and names, so check each setting. The assistant never runs a flow, so click Run yourself.
What Group By Aggregate does
Group By Aggregate turns many rows into one row per distinct value of the group column. Every other column you want to keep needs an aggregation; the result has only the group columns and the aggregated columns.
This is also why step 6 matters. Without the two Replace Values nodes, North
and north are different keys and the summary has four rows.
Result
| order_id | region | amount | ordered_at | internal_note |
|---|---|---|---|---|
| 1001 | North | 120.5 | 2024-01-03 | batch-a |
| 1002 | south | 89 | 2024-01-03 | batch-a |
| 1003 | North | null | 2024-01-04 | batch-b |
| 1004 | South | -5 | 2024-01-04 | refund |
| 1005 | null | 42.25 | 2024-01-05 | batch-b |
| 1006 | north | 210 | 2024-01-06 | batch-c |
| region | total_salesnew | num_ordersnew |
|---|---|---|
| North | 330.5 | 2 |
| South | 89 | 1 |
| Unknown | 42.25 | 1 |
Check the result
- The output has exactly three rows:
North,South,Unknown. total_salesadds up to 461.75. That is the sum of the four positive amounts (120.50 + 89.00 + 42.25 + 210.00); the refund and the missing amount are not in it.num_ordersadds up to 4, one per surviving order.
If you see a north row, a Replace Values node is missing or misspelled. If the
total is 456.75, the refund got through: check the Filter Rows node.
Exported Python
Click Export in the editor toolbar. The pandas tab shows a standalone
script. The input frame is named after the dataset, and consecutive steps fuse
into method chains. The _filter_value helper at the top compares the Filter
Rows value, saved as the text '0', as a number because amount is numeric.
Fill Nulls is a short loop that fills only the listed columns the value fits:
import pandas as pd
def _filter_value(df, column, value):
"""Type a comparison value like its column: text becomes a number on a numeric column."""
if isinstance(value, list):
items = [_filter_value(df, column, v) for v in value]
# One float makes every item a float: polars types a list by its first item.
return [float(v) for v in items] if any(isinstance(v, float) for v in items) else items
numeric = pd.api.types.is_numeric_dtype(df[column]) and not pd.api.types.is_bool_dtype(df[column])
if not isinstance(value, str) or not numeric:
return value
try:
return int(value)
except ValueError:
pass
try:
return float(value)
except ValueError:
raise ValueError(f"Value {value!r} is not a number, but column {column!r} is numeric.") from None
df_sales = pd.read_csv('sales.csv')
df_sales = (
df_sales.drop(columns=['internal_note'])
.assign(amount=lambda _d: _d['amount'].astype('float64'), ordered_at=lambda _d: pd.to_datetime(_d['ordered_at']))
.dropna(subset='amount')
.loc[lambda _d: _d['amount'] > _filter_value(_d, 'amount', '0')]
.assign(region=lambda _d: _d['region'].replace('north', 'North'))
.assign(region=lambda _d: _d['region'].replace('south', 'South'))
)
df_sales = df_sales.copy()
for _col in ['region']:
try:
_fill = pd.array(['Unknown'], dtype=df_sales[_col].dtype)[0]
except (ValueError, TypeError):
continue # the value does not fit this column's type
df_sales[_col] = df_sales[_col].fillna(_fill)
df_sales = (
df_sales.groupby('region', dropna=False)
.agg({'amount': 'sum', 'order_id': 'count'})
.reset_index()
.rename(columns={'amount': 'total_sales', 'order_id': 'num_orders'})
.sort_values('total_sales', ascending=False)
)
df_sales.to_csv('sales_summary.csv', index=False)Run it next to sales.csv and sales_summary.csv contains the three rows from
the result table. The polars tab writes the same file.
Pitfalls
- Group By Aggregate drops columns that have no aggregation.
ordered_atis not in the output because it is neither a group column nor aggregated. Add it to Aggregations (for examplemax) if you need the latest order date. - Drop Nulls with an empty subset checks every column. Here that would also remove order 1005 and its 42.25 of revenue.
- Count counts non-null values.
order_idis never null, so its count is the number of orders. Counting a column with gaps gives a smaller number.
Variations
- Revenue per region and month: add Extract Date Parts on
ordered_atwith theyearandmonthparts, then addordered_at_yearandordered_at_monthto the group columns. Time Series Analysis walks through this pattern. - A daily summary: attach a schedule to run the flow every morning.