example_data_manipulation_pandascore — Python  ↔  C++

The same 14-stage e-commerce analytics pipeline, left in Python on the pandasCore bindings and right in C++ on the native pandas::DataFrame / pandas::Series API. Each row lines the two up so corresponding operations sit together; blank cells mark lines that exist on only one side (e.g. the C++ build banner, or the explicit casts the C++ surface needs). Every stage computes the same result.

pyPython — example_data_manipulation_pandascore.py c++C++ — example_data_manipulation_pandascore.cpp
1#!/usr/bin/env python31// ============================================================================
2r"""2// example_data_manipulation_pandascore.cpp
 3//
3pandasCore — data-manipulation example (standalone, pandasCore only).4// PandasCore — data-manipulation example (standalone, PandasCore C++ only).
4 5//
5A simplified, pandasCore-ONLY version of example_data_manipulation_parity_showcase.py:6// A line-for-line C++ port of examples/example_data_manipulation_pandascore.py:
6the same readable end-to-end analytics pipeline (e-commerce orders), but with no7// the same readable end-to-end analytics pipeline (12 e-commerce orders) walked
7pandas import and no comparison. Every stage runs on a pandasCore DataFrame and8// through all 14 stages, but on the native PandasCore C++ API
8prints its result, so the file doubles as a plain usage example of the library.9// (pandas::DataFrame / pandas::Series) instead of the Python bindings. Every
 10// stage runs on a pandasCore DataFrame and prints its result, so the file
 11// doubles as a plain usage example of the C++ library and can be read side by
 12// side with the Python version. A few stages are a little more explicit than
 13// their pandas counterparts; each such line carries a short note inline.
9 14//
10Run it directly: it builds the frame and walks all 14 stages. 
11  
12See example_data_manipulation_pandascore.cpp for the C++ port of this same15// See example_data_manipulation_pandascore.py for the Python original, and
1314-stage pipeline on the native PandasCore C++ API (pandas::DataFrame /16// example_data_manipulation_parity_showcase.py for the full side-by-side run
14pandas::Series), and example_data_manipulation_parity_showcase.py for the full17// where each of these 14 stages is asserted byte-identical to pandas 2.2.2.
15side-by-side comparison, where each of these 14 stages is run on BOTH pandasCore18//
16and pandas 2.2.2 and asserted byte-identical.19// ---------------------------------------------------------------------------
17""" 
 20// Build (standalone, Release; from a "x64 Native Tools" prompt or after calling
 21// vcvars64.bat). Needs vcpkg (HDF5) and the PandasCore / NumpyCore libs:
 22// set VCPKG_ROOT=D:\Projects\vcpkg\installed\x64-windows
 23// cl /std:c++20 /EHsc /MD /O2 /bigobj /DNOMINMAX /DH5_BUILT_AS_DYNAMIC_LIB ^
 24// /D_CRT_SECURE_NO_WARNINGS /I. /I"%VCPKG_ROOT%\include" ^
 25// examples\example_data_manipulation_pandascore.cpp /Fo:temp\ ^
 26// /Fe:temp\example_data_manipulation_pandascore.exe ^
 27// /link /LIBPATH:x64\Release /LIBPATH:"%VCPKG_ROOT%\lib" ^
 28// PandasCore.lib NumpyCore.lib hdf5.lib hdf5_cpp.lib hdf5_hl.lib hdf5_hl_cpp.lib
 29//
 30// Run (needs PandasCore.dll / NumpyCore.dll / HDF5 DLLs on PATH; x64\Release
 31// holds the first two):
 32// temp\example_data_manipulation_pandascore.exe
 33// ============================================================================
18 34 
19import os35#include <iostream>
20import sys36#include <limits>
 37#include <string>
 38#include <variant>
 39#include <vector>
21 40 
22_BUILD_DIR = r"D:\Projects\Cpp2\x64\Release"41#include "../pandas/pd_dataframe.h" // pandas::Series, pandas::DataFrame, pandas::cut
23sys.path.insert(0, _BUILD_DIR) 
24os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE" 
25if hasattr(os, "add_dll_directory"): 
26 os.add_dll_directory(_BUILD_DIR) 
27  
28# This example uses only operations proven byte-identical between the two 
29# libraries, so you can bind `pd` to either one and get the SAME result — 
30# swap the two lines below to switch between pandasCore and real pandas. 
31import pandasCore as pd 
32# import pandas as pd 
 43// The C++ analogue of the Python `show(obj, label)` helper: print a header then
 44// the object's repr. Works for anything with .to_string() — DataFrame,
 45// Series<T>, CategoricalArray, ...
35def f_main():46template <typename T>
36 def show(obj, label):47static void show(const T& obj, const std::string& label) {
37 print(f"\n=== {label} ===")48 std::cout << "\n=== " << label << " ===\n" << obj.to_string() << "\n";
38 print(obj)49}
 50 
 51int f_main() {
 52 const double NaN = std::numeric_limits<double>::quiet_NaN();
40 # ------------------------------------------------------------------------54 // ------------------------------------------------------------------------
41 # Source data: 12 e-commerce orders.55 // Source data: 12 e-commerce orders.
 56 //
 57 // Built column-by-column with add_column<T> to preserve column order and
 58 // per-column dtypes (a std::map constructor would sort the names).
42 # ------------------------------------------------------------------------59 // ------------------------------------------------------------------------
43 orders = {60 pandas::DataFrame cdf;
44 "order_id": [101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112],61 cdf.add_column<numpy::int64> ("order_id", {101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112});
45 "customer": ["alice", "bob", "carla", "alice", "deepak", "bob",62 cdf.add_column<std::string> ("customer", {"alice", "bob", "carla", "alice", "deepak", "bob",
46 "erin", "carla", "deepak", "farid", "erin", "alice"],63 "erin", "carla", "deepak", "farid", "erin", "alice"});
47 "region": ["North", "South", "North", "West", "South", "West",64 cdf.add_column<std::string> ("region", {"North", "South", "North", "West", "South", "West",
48 "North", "South", "West", "North", "South", "West"],65 "North", "South", "West", "North", "South", "West"});
49 "category": ["Electronics", "Books", "Electronics", "Home", "Books", "Home",66 cdf.add_column<std::string> ("category", {"Electronics", "Books", "Electronics", "Home", "Books", "Home",
50 "Electronics", "Books", "Home", "Electronics", "Books", "Home"],67 "Electronics", "Books", "Home", "Electronics", "Books", "Home"});
51 "units": [3, 10, 1, 5, 7, 2, 4, 9, 6, 1, 8, 3],68 cdf.add_column<numpy::int64> ("units", {3, 10, 1, 5, 7, 2, 4, 9, 6, 1, 8, 3});
52 "unit_price": [199.0, 12.5, 999.0, 49.0, 15.0, 80.0,69 cdf.add_column<numpy::float64>("unit_price", {199.0, 12.5, 999.0, 49.0, 15.0, 80.0,
53 250.0, 11.0, 60.0, 1200.0, 14.5, 55.0],70 250.0, 11.0, 60.0, 1200.0, 14.5, 55.0});
54 "rating": [5, 4, 5, 3, 4, 2, 5, 4, 3, 5, 4, 3],71 cdf.add_column<numpy::int64> ("rating", {5, 4, 5, 3, 4, 2, 5, 4, 3, 5, 4, 3});
55 } 
56 cdf = pd.DataFrame(orders) 
57 show(cdf, "00. construct")72 show(cdf, "00. construct");
58 # ── prints ────────────────────────────────────────────────────────────73 // ── prints ──────────────────────────────────────────────────────────────
59 # order_id customer region category units unit_price rating74 // order_id customer region category units unit_price rating
60 # 0 101 alice North Electronics 3 199.0 575 // 0 101 alice North Electronics 3 199.0 5
61 # 1 102 bob South Books 10 12.5 476 // 1 102 bob South Books 10 12.5 4
62 # 2 103 carla North Electronics 1 999.0 5 
63 # ...77 // ...
64 # 11 112 alice West Home 3 55.0 378 // 11 112 alice West Home 3 55.0 3
66 # -- Stage 01: derived column revenue = units * unit_price (assign) -----80 // -- Stage 01: derived column revenue = units * unit_price (assign) ------
 81 // df["col"] is a type-erased handle, so take typed columns and cast the int
 82 // one to float before multiplying.
 83 auto units = cdf.col<numpy::int64>("units").astype<numpy::float64>();
 84 auto price = cdf.col<numpy::float64>("unit_price");
67 cdf = cdf.assign(revenue=cdf["units"] * cdf["unit_price"])85 cdf = cdf.assign("revenue", units * price);
68 show(cdf, "01. assign revenue = units * unit_price")86 show(cdf, "01. assign revenue = units * unit_price");
69 # ── prints (revenue column appended) ──────────────────────────────────87 // ── prints (revenue column appended) ──────────────────────────────────────
70 # order_id customer region category units unit_price rating revenue88 // order_id customer region category units unit_price rating revenue
71 # 0 101 alice North Electronics 3 199.0 5 597.089 // 0 101 alice North Electronics 3 199.0 5 597.0
72 # 6 107 erin North Electronics 4 250.0 5 1000.090 // 6 107 erin North Electronics 4 250.0 5 1000.0
73 # 9 110 farid North Electronics 1 1200.0 5 1200.091 // 9 110 farid North Electronics 1 1200.0 5 1200.0
75 # -- Stage 02: boolean filter revenue >= 300 -----------------------------93 // -- Stage 02: boolean filter revenue >= 300 ------------------------------
76 cstep = cdf[cdf["revenue"] >= 300].reset_index(drop=True)94 pandas::DataFrame cstep = cdf[cdf["revenue"] >= 300.0].reset_index(/*drop=*/true);
77 show(cstep, "02. filter revenue >= 300")95 show(cstep, "02. filter revenue >= 300");
78 # ── prints ────────────────────────────────────────────────────────────96 // ── prints ──────────────────────────────────────────────────────────────
79 # order_id customer region category units unit_price rating revenue97 // order_id customer region category units unit_price rating revenue
80 # 0 101 alice North Electronics 3 199.0 5 597.098 // 0 101 alice North Electronics 3 199.0 5 597.0
81 # 1 103 carla North Electronics 1 999.0 5 999.099 // 1 103 carla North Electronics 1 999.0 5 999.0
82 # 2 107 erin North Electronics 4 250.0 5 1000.0100 // 2 107 erin North Electronics 4 250.0 5 1000.0
83 # 3 109 deepak West Home 6 60.0 3 360.0101 // 3 109 deepak West Home 6 60.0 3 360.0
84 # 4 110 farid North Electronics 1 1200.0 5 1200.0102 // 4 110 farid North Electronics 1 1200.0 5 1200.0
86 # -- Stage 03: groupby + agg({dict}) (dict INSERTION order preserved) ----104 // -- Stage 03: groupby + agg({dict}) (dict INSERTION order preserved) -----
 105 // agg_ordered_flat keeps the (col, func) pair order, so the columns come out
 106 // in dict order (revenue, then units) rather than DataFrame order.
87 cg = cdf.groupby("region").agg({"revenue": "sum", "units": "mean"}).sort_index()107 pandas::DataFrame cg = cdf.groupby("region")
 108 .agg_ordered_flat({{"revenue", "sum"}, {"units", "mean"}})
 109 .sort_index(/*ascending=*/true);
88 show(cg, "03. groupby(region).agg({revenue:sum, units:mean})")110 show(cg, "03. groupby(region).agg({revenue:sum, units:mean})");
89 # ── prints (columns in dict order: revenue, then units) ───────────────111 // ── prints (columns in dict order: revenue, then units) ───────────────────
90 # revenue units112 // revenue units
91 # region113 // region
92 # North 3796.0 2.25114 // North 3796.0 2.25
93 # South 445.0 8.50115 // South 445.0 8.50
94 # West 930.0 4.00116 // West 930.0 4.00
96 # -- Stage 04: groupby named aggregation ----------------------------------118 // -- Stage 04: groupby named aggregation -----------------------------------
97 cn = cdf.groupby("category").agg(119 pandas::DataFrame cn = cdf.groupby("category").agg_named({
98 total_rev=("revenue", "sum"), avg_rating=("rating", "mean")).sort_index()120 {"total_rev", "revenue", "sum"},
 121 {"avg_rating", "rating", "mean"}}).sort_index(/*ascending=*/true);
99 show(cn, "04. groupby(category) named-agg")122 show(cn, "04. groupby(category) named-agg");
100 # ── prints ────────────────────────────────────────────────────────────123 // ── prints ──────────────────────────────────────────────────────────────
101 # total_rev avg_rating124 // total_rev avg_rating
102 # category125 // category
103 # Books 445.0 4.00126 // Books 445.0 4.00
104 # Electronics 3796.0 5.00127 // Electronics 3796.0 5.00
105 # Home 930.0 2.75128 // Home 930.0 2.75
107 # -- Stage 05: Series.where on an INT column (int -> float upcast) --------130 // -- Stage 05: Series.where on an INT column (int -> float upcast) ---------
 131 // where/mask take an NDArray<bool> cond (.values()) and a required `other`;
 132 // cast rating to float64 first so masked slots can hold NaN.
 133 auto rating = cdf.col<numpy::int64>("rating").astype<numpy::float64>();
108 cw = cdf["rating"].where(cdf["rating"] >= 4)134 auto cw = rating.where((rating >= 4.0).values(), NaN);
109 show(cw, "05. rating.where(>=4)")135 show(cw, "05. rating.where(>=4)");
110 # ── prints: masked-out -> NaN, dtype upcast to float64 ────────────────136 // ── prints: kept where cond is True, else NaN; dtype float64 ──────────────
111 # 0 5.0 / 1 4.0 / 2 5.0 / 3 NaN / ... / 11 NaN Name: rating, dtype: float64137 // 0 5.0 / 1 4.0 / 2 5.0 / 3 NaN / ... / 11 NaN Name: rating, dtype: float64
113 # -- Stage 06: Series.mask on an INT column (int -> float upcast) --------139 // -- Stage 06: Series.mask on an INT column (int -> float upcast) ----------
114 cm = cdf["rating"].mask(cdf["rating"] >= 4)140 auto cm = rating.mask((rating >= 4.0).values(), NaN);
115 show(cm, "06. rating.mask(>=4)")141 show(cm, "06. rating.mask(>=4)");
116 # ── prints: kept-where-False, dtype upcast to float64 ─────────────────142 // ── prints: kept where cond is False, else NaN; dtype float64 ─────────────
117 # 3 3.0 / 5 2.0 / 8 3.0 / 11 3.0 (rest NaN) Name: rating, dtype: float64143 // 3 3.0 / 5 2.0 / 8 3.0 / 11 3.0 (rest NaN) Name: rating, dtype: float64
119 # -- Stage 07: pivot_table region x category -> sum(revenue) -------------145 // -- Stage 07: pivot_table region x category -> sum(revenue) --------------
120 cp = cdf.pivot_table(values="revenue", index="region", columns="category",146 pandas::DataFrame cp = cdf.pivot_table("revenue", "region", "category",
121 aggfunc="sum", fill_value=0.0).sort_index()147 "sum", /*fill_value=*/0.0)
 148 .sort_index(/*ascending=*/true);
122 show(cp, "07. pivot_table(region x category, sum revenue)")149 show(cp, "07. pivot_table(region x category, sum revenue)");
123 # ── prints ────────────────────────────────────────────────────────────150 // ── prints ──────────────────────────────────────────────────────────────
124 # category Books Electronics Home151 // category Books Electronics Home
125 # region152 // region
126 # North 0.0 3796.0 0.0153 // North 0.0 3796.0 0.0
127 # South 445.0 0.0 0.0154 // South 445.0 0.0 0.0
128 # West 0.0 0.0 930.0155 // West 0.0 0.0 930.0
130 # -- Stage 08: left-merge with region metadata ----------------------------157 // -- Stage 08: left-merge with region metadata -----------------------------
 158 // Note the C++ argument order: merge(right, how, on).
131 region_meta = {"region": ["North", "South", "West"],159 pandas::DataFrame meta;
132 "manager": ["Nadia", "Sven", "Wendy"]}160 meta.add_column<std::string>("region", {"North", "South", "West"});
 161 meta.add_column<std::string>("manager", {"Nadia", "Sven", "Wendy"});
133 cmg = cdf.merge(pd.DataFrame(region_meta), on="region", how="left")162 pandas::DataFrame cmg = cdf.merge(meta, "left", "region");
134 show(cmg[["order_id", "region", "manager"]], "08. merge(how='left')")163 show(cmg[std::vector<std::string>{"order_id", "region", "manager"}], "08. merge(how='left')");
135 # ── prints (key projection) ───────────────────────────────────────────164 // ── prints (key projection) ───────────────────────────────────────────────
136 # order_id region manager165 // order_id region manager
137 # 0 101 North Nadia166 // 0 101 North Nadia
138 # 3 104 West Wendy167 // 3 104 West Wendy
139 # 11 112 West Wendy168 // 11 112 West Wendy
141 # -- Stage 09: nlargest(3, revenue) ---------------------------------------170 // -- Stage 09: nlargest(3, revenue) ----------------------------------------
142 ct = cdf.nlargest(3, "revenue").reset_index(drop=True)171 pandas::DataFrame ct = cdf.nlargest(3, "revenue").reset_index(/*drop=*/true);
143 show(ct, "09. nlargest(3, revenue)")172 show(ct, "09. nlargest(3, revenue)");
144 # ── prints ────────────────────────────────────────────────────────────173 // ── prints ──────────────────────────────────────────────────────────────
145 # order_id customer region category units unit_price rating revenue174 // order_id customer region category units unit_price rating revenue
146 # 0 110 farid North Electronics 1 1200.0 5 1200.0175 // 0 110 farid North Electronics 1 1200.0 5 1200.0
147 # 1 107 erin North Electronics 4 250.0 5 1000.0176 // 1 107 erin North Electronics 4 250.0 5 1000.0
148 # 2 103 carla North Electronics 1 999.0 5 999.0177 // 2 103 carla North Electronics 1 999.0 5 999.0
150 # -- Stage 10: string accessor customer.str.upper() ----------------------179 // -- Stage 10: string accessor customer.str.upper() -----------------------
 180 // str().upper() returns std::vector<std::string>; wrap it in a Series to print.
151 cs = cdf["customer"].str.upper()181 pandas::Series<std::string> cs(cdf.col<std::string>("customer").str().upper(), "customer");
152 show(cs, "10. customer.str.upper()")182 show(cs, "10. customer.str.upper()");
153 # ── prints: ALICE / BOB / CARLA / ... / ALICE dtype: object ─────────183 // ── prints: ALICE / BOB / CARLA / ... / ALICE dtype: object ─────────────
155 # -- Stage 11: cut(revenue) into tiers ------------------------------------185 // -- Stage 11: cut(revenue) into tiers -------------------------------------
 186 // cut takes a std::vector<double> and returns a CutResult whose `codes` are
 187 // an ordered CategoricalArray (small < medium < large).
 188 auto rev = cdf.col<numpy::float64>("revenue");
 189 std::vector<double> revv;
 190 revv.reserve(rev.size());
 191 for (size_t i = 0; i < rev.size(); ++i) revv.push_back(rev[i]);
 192 std::variant<int, std::vector<double>> edges = std::vector<double>{0, 100, 500, 100000};
156 cb = pd.cut(cdf["revenue"], bins=[0, 100, 500, 100000],193 auto cb = pandas::cut<double>(revv, edges, /*right=*/true, {"small", "medium", "large"});
157 labels=["small", "medium", "large"]) 
158 show(cb, "11. cut(revenue) -> small/medium/large")194 show(cb.codes, "11. cut(revenue) -> small/medium/large");
159 # ── prints an ordered Categorical (small < medium < large), length 12 ─195 // ── prints a CategoricalArray, length 12 (same codes as pandas; the repr is
 196 // a Categorical array rather than a categorical Series) ─────────────────
160 # ['large', 'medium', 'large', 'medium', 'medium', ..., 'large', 'medium', 'medium']197 // ['large', 'medium', 'large', 'medium', 'medium', 'medium', 'large', 'small',
 198 // 'medium', 'large', 'medium', 'medium']
161 # Categories (3, object): ['small' < 'medium' < 'large']199 // Categories (3, ordered): ['small', 'medium', 'large']
163 # -- Stage 12: value_counts -----------------------------------------------201 // -- Stage 12: value_counts ------------------------------------------------
164 cv = cdf["region"].value_counts().sort_index()202 pandas::Series<numpy::int64> cv =
 203 cdf.col<std::string>("region").value_counts().sort_index(/*ascending=*/true);
165 show(cv, "12. region.value_counts()")204 show(cv, "12. region.value_counts()");
166 # ── prints North 4 / South 4 / West 4 Name: count, dtype: int64 ────205 // ── prints North 4 / South 4 / West 4 Name: count, dtype: int64 ────────
168 # -- Stage 13: drop_duplicates(subset='customer') -------------------------207 // -- Stage 13: drop_duplicates(subset='customer') --------------------------
169 cu = cdf.drop_duplicates(subset="customer").reset_index(drop=True)208 pandas::DataFrame cu = cdf.drop_duplicates({"customer"}).reset_index(/*drop=*/true);
170 show(cu, "13. drop_duplicates(subset='customer')")209 show(cu, "13. drop_duplicates(subset='customer')");
171 # ── prints the first row per unique customer (6 rows) ─────────────────210 // ── prints the first row per unique customer (6 rows) ─────────────────────
172 # order_id customer region category units unit_price rating revenue211 // order_id customer region category units unit_price rating revenue
173 # 0 101 alice North Electronics 3 199.0 5 597.0212 // 0 101 alice North Electronics 3 199.0 5 597.0
174 # 1 102 bob South Books 10 12.5 4 125.0213 // 1 102 bob South Books 10 12.5 4 125.0
175 # 5 110 farid North Electronics 1 1200.0 5 1200.0214 // 5 110 farid North Electronics 1 1200.0 5 1200.0
177 print(f"\nRESULT: 14 stages executed on '{pd.__name__}'.")216 std::cout << "\nRESULT: 14 stages executed on 'pandasCore' (C++).\n";
178 return 0217 return 0;
 218}
179 219 
180  
181if __name__ == "__main__":220int main() {
182 sys.exit(f_main())221 return f_main();
 222}