IntervalIndex ============= .. cpp:class:: pandas::IntervalIndex Index class for axis labels in pandas data structures. Example ------- .. code-block:: cpp #include using namespace pandas; // Create IntervalIndex IntervalIndex idx({1, 2, 3}, "my_index"); size_t len = idx.size(); Constructors ------------ .. list-table:: :widths: 55 25 20 :header-rows: 1 * - Signature - Location - Example * - ``explicit IntervalIndex(const IntervalArray& array, const std::optional& name = std::nullopt)`` - pd_interval_index.h:144 - :ref:`View ` * - ``explicit IntervalIndex(IntervalArray&& array, const std::optional& name = std::nullopt)`` - pd_interval_index.h:153 - :ref:`View ` * - ``IntervalIndex(const IntervalIndex& other)`` - pd_interval_index.h:162 - :ref:`View ` * - ``IntervalIndex(IntervalIndex&& other) noexcept = default`` - pd_interval_index.h:171 - :ref:`View ` Construction ------------ .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``static IntervalIndex from_arrays( const std::vector& left, const std::vector& right, IntervalClosed closed = IntervalClosed::Right, const std::optional& name = std::nullopt, bool copy = false, const std::string& dtype = "")`` - static IntervalIndex - pd_interval_index.h:203 - :ref:`View ` * - ``static IntervalIndex from_arrays( const numpy::NDArray& left, const numpy::NDArray& right, IntervalClosed closed = IntervalClosed::Right, const std::optional& name = std::nullopt, bool copy = false, const std::string& dtype = "")`` - static IntervalIndex - pd_interval_index.h:231 - :ref:`View ` * - ``static IntervalIndex from_breaks( const std::vector& breaks, IntervalClosed closed = IntervalClosed::Right, const std::optional& name = std::nullopt, bool copy = false, const std::string& dtype = "")`` - static IntervalIndex - pd_interval_index.h:260 - :ref:`View ` * - ``static IntervalIndex from_breaks( const numpy::NDArray& breaks, IntervalClosed closed = IntervalClosed::Right, const std::optional& name = std::nullopt, bool copy = false, const std::string& dtype = "")`` - static IntervalIndex - pd_interval_index.h:286 - :ref:`View ` * - ``static IntervalIndex from_tuples( const std::vector>& data, IntervalClosed closed = IntervalClosed::Right, const std::optional& name = std::nullopt, bool copy = false, const std::string& dtype = "")`` - static IntervalIndex - pd_interval_index.h:313 - :ref:`View ` Indexing / Selection -------------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``get_indexer_non_unique(const IntervalIndex& target) const`` - - pd_interval_index.h:1441 - :ref:`View ` * - ``IntervalIndex get_level_values(int level = 0) const`` - IntervalIndex - pd_interval_index.h:1751 - :ref:`View ` * - ``size_t get_slice_bound(const std::pair& label, const std::string& side = "left") const`` - size_t - pd_interval_index.h:1364 - :ref:`View ` * - ``std::string get_string(size_t i) const`` - std::string - pd_interval_index.h:735 - :ref:`View ` * - ``std::string get_value_str(size_t index) const override`` - std::string - pd_interval_index.h:723 - :ref:`View ` * - ``IntervalIndex where(const numpy::NDArray& cond, const std::optional>& other = std::nullopt) const`` - IntervalIndex - pd_interval_index.h:1643 - :ref:`View ` Data Manipulation ----------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``IntervalIndex drop_duplicates(const std::string& keep = "first") const`` - IntervalIndex - pd_interval_index.h:979 - :ref:`View ` * - ``IntervalIndex droplevel(int level = 0) const`` - IntervalIndex - pd_interval_index.h:1763 - :ref:`View ` * - ``IntervalIndex insert(size_t loc, const std::pair& item) const`` - IntervalIndex - pd_interval_index.h:1084 - :ref:`View ` * - ``std::pair> reindex( const IntervalIndex& target, const std::string& method = "", std::optional level = std::nullopt, std::optional limit = std::nullopt, std::optional tolerance = std::nullopt) const`` - std::pair> - pd_interval_index.h:1562 - :ref:`View ` * - ``IntervalIndex rename(const std::optional& new_name, bool inplace = false, std::optional name = std::nullopt) const`` - IntervalIndex - pd_interval_index.h:757 - :ref:`View ` * - ``IntervalIndex set_names(const std::optional& names, std::optional level = std::nullopt, bool inplace = false) const`` - IntervalIndex - pd_interval_index.h:1698 - :ref:`View ` Statistics ---------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``std::optional> max(bool skipna = true, std::optional axis = std::nullopt) const`` - std::optional> - pd_interval_index.h:830 - :ref:`View ` * - ``std::optional> min(bool skipna = true, std::optional axis = std::nullopt) const`` - std::optional> - pd_interval_index.h:816 - :ref:`View ` Aggregation ----------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``std::unordered_map> groupby(KeyFunc key_func, std::optional values = std::nullopt) const`` - std::unordered_map> - pd_interval_index.h:1816 - :ref:`View ` * - ``std::unordered_map> groupby( const std::vector& values) const`` - std::unordered_map> - pd_interval_index.h:1848 - :ref:`View ` * - ``IntervalIndex map(Func mapper, const std::string& na_action = "") const`` - IntervalIndex - pd_interval_index.h:1616 - :ref:`View ` Arithmetic ---------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``const std::string& subtype_override() const`` - const std::string& - pd_interval_index.h:537 - :ref:`View ` Comparison ---------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``numpy::NDArray left() const`` - numpy::NDArray - pd_interval_index.h:344 - :ref:`View ` * - ``numpy::NDArray length() const`` - numpy::NDArray - pd_interval_index.h:366 - :ref:`View ` * - ``IntervalArray new_arr(values, arr.closed())`` - IntervalArray - pd_interval_index.h:1939 - * - ``IntervalArray new_arr(values, arr.closed())`` - IntervalArray - pd_interval_index.h:1959 - * - ``IntervalArray new_arr(result, arr1.closed())`` - IntervalArray - pd_interval_index.h:2028 - * - ``IntervalArray new_array(values, this->closed())`` - IntervalArray - pd_interval_index.h:1100 - * - ``IntervalArray new_array(values, this->closed())`` - IntervalArray - pd_interval_index.h:1189 - * - ``IntervalArray new_array(values, this->closed())`` - IntervalArray - pd_interval_index.h:1212 - * - ``IntervalArray new_array(values, this->closed())`` - IntervalArray - pd_interval_index.h:1545 - * - ``IntervalArray new_array(values, this->closed())`` - IntervalArray - pd_interval_index.h:1601 - * - ``IntervalArray new_array(values, this->closed())`` - IntervalArray - pd_interval_index.h:1633 - * - ``IntervalArray new_array(values, this->closed())`` - IntervalArray - pd_interval_index.h:1660 - * - ``IntervalArray new_array(values, this->closed())`` - IntervalArray - pd_interval_index.h:1687 - * - ``IntervalArray new_array(values, this->closed())`` - IntervalArray - pd_interval_index.h:1741 - Sorting ------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``size_t searchsorted(const std::pair& value, const std::string& side = "left", std::optional> sorter = std::nullopt) const`` - size_t - pd_interval_index.h:1477 - :ref:`View ` Reshaping --------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``FrameData to_frame(bool index = true, const std::optional& name = std::nullopt) const`` - FrameData - pd_interval_index.h:2074 - :ref:`View ` * - ``IntervalIndex transpose() const`` - IntervalIndex - pd_interval_index.h:1236 - :ref:`View ` Combining --------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``IntervalIndex join(const IntervalIndex& other, const std::string& how = "left", std::optional level = std::nullopt, bool return_indexers = false, bool sort = false) const`` - IntervalIndex - pd_interval_index.h:1890 - :ref:`View ` Time Series ----------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``std::optional> asof(T where, std::optional label = std::nullopt) const`` - std::optional> - pd_interval_index.h:1314 - :ref:`View ` * - ``numpy::NDArray asof_locs(const numpy::NDArray& where, std::optional> mask = std::nullopt) const`` - numpy::NDArray - pd_interval_index.h:1336 - :ref:`View ` * - ``numpy::NDArray diff(int64_t periods = 1) const`` - numpy::NDArray - pd_interval_index.h:1109 - :ref:`View ` * - ``IntervalIndex shift(int64_t periods = 1, std::optional freq = std::nullopt) const`` - IntervalIndex - pd_interval_index.h:1159 - :ref:`View ` I/O --- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``IntervalIndex to_flat_index() const`` - IntervalIndex - pd_interval_index.h:1243 - :ref:`View ` * - ``std::vector> to_numpy( bool copy = true, const std::pair& na_value = std::pair{T{0}, T{0}}) const`` - std::vector> - pd_interval_index.h:1255 - :ref:`View ` * - ``SeriesData to_series(const std::optional& index = std::nullopt, const std::optional& name = std::nullopt) const`` - SeriesData - pd_interval_index.h:2141 - :ref:`View ` * - ``std::string to_string() const override`` - std::string - pd_interval_index.h:649 - :ref:`View ` * - ``std::vector>> to_tuples() const`` - std::vector>> - pd_interval_index.h:519 - :ref:`View ` * - ``std::vector>> tolist() const`` - std::vector>> - pd_interval_index.h:1274 - :ref:`View ` Conversion ---------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``IntervalIndex astype(const std::string& dtype, bool copy = true) const`` - IntervalIndex - pd_interval_index.h:1782 - :ref:`View ` * - ``IntervalIndex copy() const`` - IntervalIndex - pd_interval_index.h:770 - :ref:`View ` * - ``IntervalIndex infer_objects() const`` - IntervalIndex - pd_interval_index.h:1712 - :ref:`View ` * - ``IntervalIndex view() const`` - IntervalIndex - pd_interval_index.h:1228 - :ref:`View ` Set Operations -------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``std::vector duplicated(const std::string& keep = "first") const`` - std::vector - pd_interval_index.h:1038 - :ref:`View ` * - ``IntervalIndex union_(const IntervalIndex& other, bool sort = true) const`` - IntervalIndex - pd_interval_index.h:1973 - :ref:`View ` * - ``IntervalIndex unique() const`` - IntervalIndex - pd_interval_index.h:960 - :ref:`View ` Type Checking ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``bool is_(const IntervalIndex& other) const`` - bool - pd_interval_index.h:1772 - :ref:`View ` * - ``bool is_boolean() const`` - bool - pd_interval_index.h:873 - :ref:`View ` * - ``bool is_categorical() const`` - bool - pd_interval_index.h:880 - :ref:`View ` * - ``BooleanArray is_empty() const`` - BooleanArray - pd_interval_index.h:412 - :ref:`View ` * - ``bool is_floating() const`` - bool - pd_interval_index.h:887 - :ref:`View ` * - ``bool is_integer() const`` - bool - pd_interval_index.h:894 - :ref:`View ` * - ``bool is_interval() const`` - bool - pd_interval_index.h:866 - :ref:`View ` * - ``bool is_left_closed() const`` - bool - pd_interval_index.h:391 - :ref:`View ` * - ``bool is_non_overlapping_monotonic() const`` - bool - pd_interval_index.h:439 - :ref:`View ` * - ``bool is_numeric() const`` - bool - pd_interval_index.h:901 - :ref:`View ` * - ``bool is_object() const`` - bool - pd_interval_index.h:908 - :ref:`View ` * - ``bool is_overlapping() const`` - bool - pd_interval_index.h:424 - :ref:`View ` * - ``bool is_right_closed() const`` - bool - pd_interval_index.h:398 - :ref:`View ` Other Methods ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``bool all(bool skipna = true) const`` - bool - pd_interval_index.h:783 - :ref:`View ` * - ``static bool all_values_integer(const std::vector& values)`` - static bool - pd_interval_index.h:63 - * - ``bool any(bool skipna = true) const`` - bool - pd_interval_index.h:801 - :ref:`View ` * - ``numpy::int64 argmax() const`` - numpy::int64 - pd_interval_index.h:848 - :ref:`View ` * - ``numpy::int64 argmin() const`` - numpy::int64 - pd_interval_index.h:841 - :ref:`View ` * - ``IntervalArray arr(out, this->closed())`` - IntervalArray - pd_interval_index.h:972 - :ref:`View ` * - ``IntervalArray arr(result_vals, this->closed())`` - IntervalArray - pd_interval_index.h:1032 - :ref:`View ` * - ``std::unique_ptr clone() const override`` - std::unique_ptr - pd_interval_index.h:561 - :ref:`View ` * - ``IntervalClosed closed() const`` - IntervalClosed - pd_interval_index.h:377 - :ref:`View ` * - ``std::string closed_string() const`` - std::string - pd_interval_index.h:384 - :ref:`View ` * - ``void compute_is_overlapping() const`` - void - pd_interval_index.h:74 - * - ``BooleanArray contains(T value) const`` - BooleanArray - pd_interval_index.h:456 - :ref:`View ` * - ``BooleanArray contains(const numpy::NDArray& values) const`` - BooleanArray - pd_interval_index.h:466 - :ref:`View ` * - ``IntervalIndex delete_(size_t loc) const`` - IntervalIndex - pd_interval_index.h:1924 - :ref:`View ` * - ``IntervalIndex delete_(const std::vector& locs) const`` - IntervalIndex - pd_interval_index.h:1948 - :ref:`View ` * - ``std::string dtype_indent(14, ' ')`` - std::string - pd_interval_index.h:704 - * - ``std::string dtype_name() const override`` - std::string - pd_interval_index.h:544 - :ref:`View ` * - ``oss << fmt_td(val->first) << ", " << fmt_td(val->second)`` - oss << - pd_interval_index.h:601 - * - ``oss << fmt_ts(val->first) << ", " << fmt_ts(val->second)`` - oss << - pd_interval_index.h:639 - * - ``std::vector format(bool na_rep_as_string = true, std::nullptr_t formatter = nullptr, const std::string& na_rep = "NaN", bool name = false) const`` - std::vector - pd_interval_index.h:1286 - :ref:`View ` * - ``std::string format_interval(size_t index) const`` - std::string - pd_interval_index.h:575 - :ref:`View ` * - ``bool holds_integer() const`` - bool - pd_interval_index.h:859 - :ref:`View ` * - ``std::string indent(15, ' ')`` - std::string - pd_interval_index.h:655 - * - ``std::string inferred_type() const override`` - std::string - pd_interval_index.h:554 - :ref:`View ` * - ``std::pair item() const`` - std::pair - pd_interval_index.h:930 - :ref:`View ` * - ``size_t memory_usage(bool deep = false) const`` - size_t - pd_interval_index.h:921 - :ref:`View ` * - ``FloatingArray mid() const`` - FloatingArray - pd_interval_index.h:359 - :ref:`View ` * - ``BooleanArray overlaps(T other_left, T other_right) const`` - BooleanArray - pd_interval_index.h:477 - :ref:`View ` * - ``BooleanArray overlaps(T other_left, T other_right, IntervalClosed other_closed) const`` - BooleanArray - pd_interval_index.h:489 - :ref:`View ` * - ``IntervalIndex putmask(const numpy::NDArray& mask, const std::pair& value) const`` - IntervalIndex - pd_interval_index.h:1670 - :ref:`View ` * - ``IntervalIndex ravel() const`` - IntervalIndex - pd_interval_index.h:1220 - :ref:`View ` * - ``IntervalIndex repeat(size_t repeats, std::optional axis = std::nullopt) const`` - IntervalIndex - pd_interval_index.h:1199 - :ref:`View ` * - ``std::string repr() const override`` - std::string - pd_interval_index.h:716 - :ref:`View ` * - ``IntervalIndex result(\*this)`` - IntervalIndex - pd_interval_index.h:762 - :ref:`View ` * - ``numpy::NDArray right() const`` - numpy::NDArray - pd_interval_index.h:351 - :ref:`View ` * - ``IntervalIndex round(int decimals = 0) const`` - IntervalIndex - pd_interval_index.h:1721 - :ref:`View ` * - ``IntervalIndex set_closed(IntervalClosed new_closed) const`` - IntervalIndex - pd_interval_index.h:503 - :ref:`View ` * - ``IntervalIndex set_closed(const std::string& new_closed) const`` - IntervalIndex - pd_interval_index.h:511 - :ref:`View ` * - ``void set_subtype_override(const std::string& override_str)`` - void - pd_interval_index.h:530 - :ref:`View ` * - ``std::vector slice_indexer( const std::optional>& start = std::nullopt, const std::optional>& end = std::nullopt, size_t step = 1) const`` - std::vector - pd_interval_index.h:1420 - :ref:`View ` * - ``std::pair slice_locs( const std::optional>& start = std::nullopt, const std::optional>& end = std::nullopt, size_t step = 1) const`` - std::pair - pd_interval_index.h:1385 - :ref:`View ` * - ``IntervalIndex sort(bool ascending = true) const`` - IntervalIndex - pd_interval_index.h:1509 - :ref:`View ` * - ``std::pair> sortlevel( int level = 0, bool ascending = true, const std::string& na_position = "last", bool sort_remaining = true) const`` - std::pair> - pd_interval_index.h:1522 - :ref:`View ` * - ``StringMethods> str() const`` - StringMethods> - pd_interval_index.h:743 - :ref:`View ` * - ``IndexTypeId type_id() const override`` - IndexTypeId - pd_interval_index.h:565 - :ref:`View ` Code Examples ------------- The following examples are extracted from the test suite. .. _example-intervalindex-intervalindex-0: .. dropdown:: IntervalIndex (pd_test_5_all.cpp:1350) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1340 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } // --- cpp_f_test_pandas_advanced_indexing_compare_full_1053.cpp --- void f_test_pandas_advanced_indexing_compare_full_1053() { std::cout << "========= f_test_pandas_advanced_indexing_compare_full_1053 ======="; int local_fail = 0; // Expected from pandas: str(pd.cut(range(4), bins=2).categories) std::string expected = "IntervalIndex([(-0.003, 1.5], (1.5, 3.0]], dtype='interval[float64, right]')"; // Placeholder: cut() + categories accessor needed in C++ API // pandas_tests::check(result_categories.to_string() == expected, "binning.cut_categories.str"); pandas_tests::check(true, "binning.cut_categories.str (expected value captured)", local_fail); if (local_fail > 0) { std::cout << " [FAIL] : in f_test_pandas_advanced_indexing_compare_full_1053() : " << local_fail << " checks failed" << std::endl; throw std::runtime_error("f_test_pandas_advanced_indexing_compare_full_1053 failed"); } std::cout << " -> tests passed" << std::endl; } .. _example-intervalindex-intervalindex-1: .. dropdown:: IntervalIndex (pd_test_5_all.cpp:1350) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1340 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } // --- cpp_f_test_pandas_advanced_indexing_compare_full_1053.cpp --- void f_test_pandas_advanced_indexing_compare_full_1053() { std::cout << "========= f_test_pandas_advanced_indexing_compare_full_1053 ======="; int local_fail = 0; // Expected from pandas: str(pd.cut(range(4), bins=2).categories) std::string expected = "IntervalIndex([(-0.003, 1.5], (1.5, 3.0]], dtype='interval[float64, right]')"; // Placeholder: cut() + categories accessor needed in C++ API // pandas_tests::check(result_categories.to_string() == expected, "binning.cut_categories.str"); pandas_tests::check(true, "binning.cut_categories.str (expected value captured)", local_fail); if (local_fail > 0) { std::cout << " [FAIL] : in f_test_pandas_advanced_indexing_compare_full_1053() : " << local_fail << " checks failed" << std::endl; throw std::runtime_error("f_test_pandas_advanced_indexing_compare_full_1053 failed"); } std::cout << " -> tests passed" << std::endl; } .. _example-intervalindex-intervalindex-2: .. dropdown:: IntervalIndex (pd_test_5_all.cpp:1350) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1340 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } // --- cpp_f_test_pandas_advanced_indexing_compare_full_1053.cpp --- void f_test_pandas_advanced_indexing_compare_full_1053() { std::cout << "========= f_test_pandas_advanced_indexing_compare_full_1053 ======="; int local_fail = 0; // Expected from pandas: str(pd.cut(range(4), bins=2).categories) std::string expected = "IntervalIndex([(-0.003, 1.5], (1.5, 3.0]], dtype='interval[float64, right]')"; // Placeholder: cut() + categories accessor needed in C++ API // pandas_tests::check(result_categories.to_string() == expected, "binning.cut_categories.str"); pandas_tests::check(true, "binning.cut_categories.str (expected value captured)", local_fail); if (local_fail > 0) { std::cout << " [FAIL] : in f_test_pandas_advanced_indexing_compare_full_1053() : " << local_fail << " checks failed" << std::endl; throw std::runtime_error("f_test_pandas_advanced_indexing_compare_full_1053 failed"); } std::cout << " -> tests passed" << std::endl; } .. _example-intervalindex-intervalindex-3: .. dropdown:: IntervalIndex (pd_test_5_all.cpp:1350) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1340 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } // --- cpp_f_test_pandas_advanced_indexing_compare_full_1053.cpp --- void f_test_pandas_advanced_indexing_compare_full_1053() { std::cout << "========= f_test_pandas_advanced_indexing_compare_full_1053 ======="; int local_fail = 0; // Expected from pandas: str(pd.cut(range(4), bins=2).categories) std::string expected = "IntervalIndex([(-0.003, 1.5], (1.5, 3.0]], dtype='interval[float64, right]')"; // Placeholder: cut() + categories accessor needed in C++ API // pandas_tests::check(result_categories.to_string() == expected, "binning.cut_categories.str"); pandas_tests::check(true, "binning.cut_categories.str (expected value captured)", local_fail); if (local_fail > 0) { std::cout << " [FAIL] : in f_test_pandas_advanced_indexing_compare_full_1053() : " << local_fail << " checks failed" << std::endl; throw std::runtime_error("f_test_pandas_advanced_indexing_compare_full_1053 failed"); } std::cout << " -> tests passed" << std::endl; } .. _example-intervalindex-from_arrays-4: .. dropdown:: from_arrays (pd_test_1_all.cpp:1994) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1984 :emphasize-lines: 11 // ============================================================================ // Test: from_arrays factory method // ============================================================================ void test_from_arrays() { std::cout << "========= IntervalArray: from_arrays ======================= "; std::vector left_vec = {0, 10, 20}; std::vector right_vec = {5, 15, 25}; auto arr = pandas::IntervalArrayInt64::from_arrays(left_vec, right_vec); if (arr.size() != 3) { std::cout << "[FAIL] : in test_from_arrays() : size" << std::endl; return; } auto interval1 = arr[1]; if (!interval1.has_value() || interval1->first != 10 || interval1->second != 15) { std::cout << "[FAIL] : in test_from_arrays() : interval values" << std::endl; return; .. _example-intervalindex-from_arrays-5: .. dropdown:: from_arrays (pd_test_1_all.cpp:1994) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1984 :emphasize-lines: 11 // ============================================================================ // Test: from_arrays factory method // ============================================================================ void test_from_arrays() { std::cout << "========= IntervalArray: from_arrays ======================= "; std::vector left_vec = {0, 10, 20}; std::vector right_vec = {5, 15, 25}; auto arr = pandas::IntervalArrayInt64::from_arrays(left_vec, right_vec); if (arr.size() != 3) { std::cout << "[FAIL] : in test_from_arrays() : size" << std::endl; return; } auto interval1 = arr[1]; if (!interval1.has_value() || interval1->first != 10 || interval1->second != 15) { std::cout << "[FAIL] : in test_from_arrays() : interval values" << std::endl; return; .. _example-intervalindex-from_breaks-6: .. dropdown:: from_breaks (pd_test_1_all.cpp:1955) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1945 :emphasize-lines: 11 } // ============================================================================ // Test: from_breaks factory method // ============================================================================ void test_from_breaks() { std::cout << "========= IntervalArray: from_breaks ======================= "; // Create from breaks std::vector breaks = {0.0, 1.0, 2.0, 3.0, 4.0}; auto arr = pandas::IntervalArrayFloat64::from_breaks(breaks); if (arr.size() != 4) { std::cout << "[FAIL] : in test_from_breaks() : size should be n-1" << std::endl; return; } // Check intervals auto interval0 = arr[0]; if (!interval0.has_value() || interval0->first != 0.0 || interval0->second != 1.0) { std::cout << "[FAIL] : in test_from_breaks() : first interval" << std::endl; .. _example-intervalindex-from_breaks-7: .. dropdown:: from_breaks (pd_test_1_all.cpp:1955) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1945 :emphasize-lines: 11 } // ============================================================================ // Test: from_breaks factory method // ============================================================================ void test_from_breaks() { std::cout << "========= IntervalArray: from_breaks ======================= "; // Create from breaks std::vector breaks = {0.0, 1.0, 2.0, 3.0, 4.0}; auto arr = pandas::IntervalArrayFloat64::from_breaks(breaks); if (arr.size() != 4) { std::cout << "[FAIL] : in test_from_breaks() : size should be n-1" << std::endl; return; } // Check intervals auto interval0 = arr[0]; if (!interval0.has_value() || interval0->first != 0.0 || interval0->second != 1.0) { std::cout << "[FAIL] : in test_from_breaks() : first interval" << std::endl; .. _example-intervalindex-from_tuples-8: .. dropdown:: from_tuples (pd_test_1_all.cpp:2022) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2012 :emphasize-lines: 11 // ============================================================================ void test_from_tuples() { std::cout << "========= IntervalArray: from_tuples ======================= "; std::vector> tuples = { {0.0, 1.5}, {1.5, 3.0}, {3.0, 4.5} }; auto arr = pandas::IntervalArrayFloat64::from_tuples(tuples); if (arr.size() != 3) { std::cout << "[FAIL] : in test_from_tuples() : size" << std::endl; return; } auto interval2 = arr[2]; if (!interval2.has_value() || interval2->first != 3.0 || interval2->second != 4.5) { std::cout << "[FAIL] : in test_from_tuples() : interval values" << std::endl; return; .. _example-intervalindex-get_indexer_non_unique-9: .. dropdown:: get_indexer_non_unique (pd_test_3_all.cpp:739) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 729 :emphasize-lines: 11 if (indexer.getElementAt({1}) != 3) { std::cout << " [FAIL] : in pd_test_3_all_index_indexers() : 'd' should be at index 3" << std::endl; throw std::runtime_error("pd_test_3_all_index_indexers failed: 'd' index"); } // "f" doesn't exist -> -1 if (indexer.getElementAt({2}) != -1) { std::cout << " [FAIL] : in pd_test_3_all_index_indexers() : 'f' should be -1" << std::endl; throw std::runtime_error("pd_test_3_all_index_indexers failed: 'f' index"); } // Test get_indexer_non_unique() std::vector target2 = {"a", "c", "z"}; // "z" doesn't exist pandas::Index target_idx(target2); auto [indexer2, missing] = idx.get_indexer_non_unique(target_idx); if (indexer2.getSize() < 2) { std::cout << " [FAIL] : in pd_test_3_all_index_indexers() : get_indexer_non_unique size too small" << std::endl; throw std::runtime_error("pd_test_3_all_index_indexers failed: get_indexer_non_unique size"); } // Test slice_indexer() .. _example-intervalindex-get_level_values-10: .. dropdown:: get_level_values (pd_test_3_all.cpp:4524) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 4514 :emphasize-lines: 11 } std::cout << " -> tests passed" << std::endl; } void pd_test_3_all_interval_index_get_level_values_droplevel() { std::cout << "========= IntervalIndex.get_level_values/droplevel() "; pandas::IntervalIndex64 idx = pandas::IntervalIndex64::from_breaks({0, 10, 20, 30}); // get_level_values(0) should work pandas::IntervalIndex64 level_vals = idx.get_level_values(0); if (level_vals.size() != idx.size()) { throw std::runtime_error("get_level_values(0) size mismatch"); } // get_level_values(1) should throw bool threw = false; try { idx.get_level_values(1); } catch (const std::out_of_range&) { .. _example-intervalindex-get_slice_bound-11: .. dropdown:: get_slice_bound (pd_test_3_all.cpp:3644) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3634 :emphasize-lines: 11 formatted = idx.format(custom_formatter); if (formatted[0] != "val:1") { throw std::runtime_error("custom formatter failed"); } std::cout << " -> tests passed" << std::endl; } void pd_test_3_all_index_get_slice_bound() { std::cout << "========= Index.get_slice_bound() =================="; pandas::Index idx({10, 20, 30, 40, 50}); // Exact match, left side size_t bound = idx.get_slice_bound(30, "left"); if (bound != 2) { throw std::runtime_error("left bound for 30 should be 2"); } // Exact match, right side .. _example-intervalindex-get_string-12: .. dropdown:: get_string (pd_test_3_all.cpp:27746) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 27736 :emphasize-lines: 11 } } pandas::Series si({10, 20, 30}, "ints"); auto result2 = si.astype("str"); auto* str_s2 = dynamic_cast*>(result2.get()); if (!str_s2) { std::cout << " FAIL: expected Series from int" << std::endl; fail++; } else { if (str_s2->get_string(0) != "10") { std::cout << " FAIL: expected '10', got '" << str_s2->get_string(0) << "'" << std::endl; fail++; } } if (fail == 0) std::cout << " OK" << std::endl; } void pd_test_astype_datetime_to_string() { std::cout << " -- pd_test_astype_datetime_to_string --" << std::endl; .. _example-intervalindex-get_value_str-13: .. dropdown:: get_value_str (pd_test_1_all.cpp:4665) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 4655 :emphasize-lines: 11 auto corr_df = df.corr(); // Check dimensions bool passed = corr_df.nrows() == 2 && corr_df.ncols() == 2; if (!passed) { std::cout << " [FAIL] : in pd_test_aggregation_dataframe_corr() : corr should be 2x2" << std::endl; throw std::runtime_error("pd_test_aggregation_dataframe_corr failed: corr should be 2x2"); } // Diagonal should be 1.0 std::string aa = corr_df["A"].get_value_str(0); passed = std::abs(std::stod(aa) - 1.0) < 0.001; if (!passed) { std::cout << " [FAIL] : in pd_test_aggregation_dataframe_corr() : diagonal should be 1.0" << std::endl; throw std::runtime_error("pd_test_aggregation_dataframe_corr failed: diagonal should be 1.0"); } // A-B correlation should be 1.0 (perfect correlation) std::string ab = corr_df["B"].get_value_str(0); passed = std::abs(std::stod(ab) - 1.0) < 0.001; if (!passed) { .. _example-intervalindex-where-14: .. dropdown:: where (pd_test_1_all.cpp:22018) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22008 :emphasize-lines: 11 data["B"] = {5.0, 6.0, 7.0, 8.0}; pandas::DataFrame df(data); // Create condition DataFrame (values > 2) std::map> cond_data; cond_data["A"] = {false, false, true, true}; // 1<=2, 2<=2, 3>2, 4>2 cond_data["B"] = {true, true, true, true}; // all >2 pandas::DataFrame cond(cond_data); // Apply where with replacement value -1 pandas::DataFrame result = df.where(cond, -1.0); // Get column index for A - it's sorted alphabetically in std::map size_t col_a_idx = df.get_column_index("A"); size_t col_b_idx = df.get_column_index("B"); bool passed = true; std::string error_msg; // Check A column values std::string a0 = result.iat(0, col_a_idx) == -1.0 ? "ok" : "fail"; .. _example-intervalindex-drop_duplicates-15: .. dropdown:: drop_duplicates (pd_test_1_all.cpp:6639) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 6629 :emphasize-lines: 11 } } // Test drop_duplicates { std::map> dup_data; dup_data["A"] = {1, 1, 2, 2}; dup_data["B"] = {1, 1, 2, 3}; pandas::DataFrame df_dup(dup_data); auto deduped = df_dup.drop_duplicates(); // Rows 0 and 1 are duplicates (A=1, B=1), so should have 3 rows if (deduped.nrows() != 3) { std::cout << " [FAIL] : in pd_test_dataframe_manipulation() : drop_duplicates nrows != 3, got " << deduped.nrows() << std::endl; throw std::runtime_error("pd_test_dataframe_manipulation failed: drop_duplicates"); } } // Test assign { std::map> assign_data; .. _example-intervalindex-droplevel-16: .. dropdown:: droplevel (pd_test_1_all.cpp:14428) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 14418 :emphasize-lines: 11 void pd_test_multiindex_droplevel() { std::cout << "========= droplevel =================================== "; std::vector> arrays = { {"a", "a", "b"}, {"x", "y", "z"}, {"1", "2", "3"} }; pandas::MultiIndex mi = pandas::MultiIndex::from_arrays(arrays); pandas::MultiIndex dropped = mi.droplevel(1); bool passed = true; if (dropped.nlevels() != 2) { std::cout << " [FAIL] : nlevels should be 2 after drop" << std::endl; passed = false; } // Check remaining levels auto tup = dropped[0]; .. _example-intervalindex-insert-17: .. dropdown:: insert (pd_test_1_all.cpp:12028) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 12018 :emphasize-lines: 11 } std::cout << " -> tests passed" << std::endl; } void pd_test_index_insert_delete() { std::cout << "========= insert and delete ==========================="; pandas::Index idx{1, 2, 4, 5}; auto inserted = idx.insert(2, 3); bool passed = (inserted.size() == 5); passed = passed && (inserted[2] == 3); auto deleted = inserted.delete_(2); passed = passed && (deleted.size() == 4); passed = passed && deleted.equals(idx); if (!passed) { std::cout << " [FAIL] : in pd_test_index_insert_delete() : insert/delete failed" << std::endl; throw std::runtime_error("pd_test_index_insert_delete failed"); .. _example-intervalindex-reindex-18: .. dropdown:: reindex (pd_test_1_all.cpp:6708) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 6698 :emphasize-lines: 11 } } // Test reindex rows { std::map> data; data["A"] = {1.0, 2.0, 3.0}; pandas::DataFrame df(data); df = df.set_axis({"x", "y", "z"}, 0); auto reindexed = df.reindex({"x", "z", "w"}, 0); if (reindexed.nrows() != 3) { std::cout << " [FAIL] : in pd_test_dataframe_index_ops() : reindex wrong nrows" << std::endl; throw std::runtime_error("pd_test_dataframe_index_ops failed: reindex nrows"); } // 'w' should have NaN std::string val = reindexed["A"].get_value_str(2); if (!std::isnan(std::stod(val))) { std::cout << " [FAIL] : in pd_test_dataframe_index_ops() : missing label should be NaN" << std::endl; throw std::runtime_error("pd_test_dataframe_index_ops failed: reindex NaN"); } .. _example-intervalindex-rename-19: .. dropdown:: rename (pd_test_1_all.cpp:5816) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 5806 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } void pd_test_categorical_index_rename() { std::cout << "========= rename ======================================"; pandas::CategoricalArray arr({"x", "y"}); pandas::CategoricalIndex idx(arr, "old_name"); pandas::CategoricalIndex renamed = idx.rename("new_name"); bool passed = (renamed.name().has_value() && *renamed.name() == "new_name" && renamed.size() == idx.size() && renamed.categories() == idx.categories()); if (!passed) { std::cout << " [FAIL] : in pd_test_categorical_index_rename()" << std::endl; throw std::runtime_error("pd_test_categorical_index_rename failed"); } std::cout << " -> tests passed" << std::endl; } .. _example-intervalindex-set_names-20: .. dropdown:: set_names (pd_test_1_all.cpp:14519) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 14509 :emphasize-lines: 11 std::cout << "-> tests passed" << std::endl; } void pd_test_multiindex_set_names() { std::cout << "========= set_names =================================== "; std::vector> arrays = {{"a", "b"}, {"x", "y"}}; pandas::MultiIndex mi = pandas::MultiIndex::from_arrays(arrays); std::vector> new_names = {"level_a", "level_b"}; pandas::MultiIndex named = mi.set_names(new_names); bool passed = (named.names()[0] == "level_a" && named.names()[1] == "level_b"); if (!passed) { std::cout << " [FAIL] : names not set correctly" << std::endl; throw std::runtime_error("pd_test_multiindex_set_names failed"); } std::cout << "-> tests passed" << std::endl; } .. _example-intervalindex-max-21: .. dropdown:: max (pd_test_1_all.cpp:771) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 761 :emphasize-lines: 11 pandas::CategoricalArray arr = pandas::CategoricalArray::from_codes(codes, cats, true); // ordered // Test min std::optional min_val = arr.min(); if (!min_val.has_value() || *min_val != "low") { std::cout << " [FAIL] : in pd_test_categorical_array_ordered_operations() : min != 'low'" << std::endl; throw std::runtime_error("pd_test_categorical_array_ordered_operations failed: min != 'low'"); } // Test max std::optional max_val = arr.max(); if (!max_val.has_value() || *max_val != "high") { std::cout << " [FAIL] : in pd_test_categorical_array_ordered_operations() : max != 'high'" << std::endl; throw std::runtime_error("pd_test_categorical_array_ordered_operations failed: max != 'high'"); } // Test unordered throws for min/max pandas::CategoricalArray unordered = arr.as_unordered(); bool threw = false; try { unordered.min(); .. _example-intervalindex-min-22: .. dropdown:: min (pd_test_1_all.cpp:764) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 754 :emphasize-lines: 11 } void pd_test_categorical_array_ordered_operations() { std::cout << "========= CategoricalArray: ordered operations (min/max) ======================= "; std::vector cats = {"low", "medium", "high"}; std::vector codes = {0, 2, 1, 0, -1}; // low, high, medium, low, NA pandas::CategoricalArray arr = pandas::CategoricalArray::from_codes(codes, cats, true); // ordered // Test min std::optional min_val = arr.min(); if (!min_val.has_value() || *min_val != "low") { std::cout << " [FAIL] : in pd_test_categorical_array_ordered_operations() : min != 'low'" << std::endl; throw std::runtime_error("pd_test_categorical_array_ordered_operations failed: min != 'low'"); } // Test max std::optional max_val = arr.max(); if (!max_val.has_value() || *max_val != "high") { std::cout << " [FAIL] : in pd_test_categorical_array_ordered_operations() : max != 'high'" << std::endl; throw std::runtime_error("pd_test_categorical_array_ordered_operations failed: max != 'high'"); .. _example-intervalindex-groupby-23: .. dropdown:: groupby (pd_test_1_all.cpp:11495) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11485 :emphasize-lines: 11 std::cout << "========= GroupBy basic ========================="; // Create DataFrame with category column std::map> data = { {"category", {1.0, 1.0, 2.0, 2.0, 2.0}}, {"value", {10.0, 20.0, 30.0, 40.0, 50.0}} }; pandas::DataFrame df(data); // Test groupby auto grouped = df.groupby("category"); bool passed = grouped.ngroups() == 2; if (!passed) { std::cout << " [FAIL] : in pd_test_groupby_basic() : ngroups should be 2" << std::endl; throw std::runtime_error("pd_test_groupby_basic failed: ngroups should be 2"); } std::cout << " -> tests passed" << std::endl; } .. _example-intervalindex-groupby-24: .. dropdown:: groupby (pd_test_1_all.cpp:11495) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11485 :emphasize-lines: 11 std::cout << "========= GroupBy basic ========================="; // Create DataFrame with category column std::map> data = { {"category", {1.0, 1.0, 2.0, 2.0, 2.0}}, {"value", {10.0, 20.0, 30.0, 40.0, 50.0}} }; pandas::DataFrame df(data); // Test groupby auto grouped = df.groupby("category"); bool passed = grouped.ngroups() == 2; if (!passed) { std::cout << " [FAIL] : in pd_test_groupby_basic() : ngroups should be 2" << std::endl; throw std::runtime_error("pd_test_groupby_basic failed: ngroups should be 2"); } std::cout << " -> tests passed" << std::endl; } .. _example-intervalindex-map-25: .. dropdown:: map (pd_test_1_all.cpp:5839) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 5829 :emphasize-lines: 11 // Map Tests // ============================================================================ void pd_test_categorical_index_map() { std::cout << "========= map ========================================="; pandas::CategoricalArray arr({"yes", "no", "yes"}); pandas::CategoricalIndex idx(arr); std::unordered_map mapping = {{"yes", "1"}, {"no", "0"}}; pandas::CategoricalIndex mapped = idx.map(mapping); bool passed = (mapped.has_category("1") && mapped.has_category("0") && !mapped.has_category("yes") && !mapped.has_category("no")); if (!passed) { std::cout << " [FAIL] : in pd_test_categorical_index_map()" << std::endl; throw std::runtime_error("pd_test_categorical_index_map failed"); } std::cout << " -> tests passed" << std::endl; } .. _example-intervalindex-subtype_override-26: .. dropdown:: subtype_override (pd_test_3_all.cpp:24889) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 24879 :emphasize-lines: 11 return dataframe_tests_bdate_timedelta_range::pd_test_bdate_timedelta_range_main(); } // ------------------- pd_test_bdate_timedelta_range (end) --------------------------- // ------------------- pd_test_interval_type_inference (begin) --------------------------- namespace dataframe_tests_interval_type_inference { void pd_test_interval_type_inference_breaks_int() { std::cout << "========= interval_type_inference_breaks_int ======================= "; auto idx = pandas::IntervalIndex::from_breaks({0.0, 1.0, 2.0, 3.0}); if (idx.subtype_override() != "int64") throw std::runtime_error("expected subtype_override 'int64', got '" + idx.subtype_override() + "'"); std::string dtype = idx.dtype_name(); if (dtype.find("int64") == std::string::npos) throw std::runtime_error("expected dtype containing 'int64', got '" + dtype + "'"); std::string fmt = idx.format_interval(0); if (fmt.find('.') != std::string::npos) throw std::runtime_error("expected integer format without decimal, got '" + fmt + "'"); std::cout << " -> tests passed" << std::endl; } .. _example-intervalindex-left-27: .. dropdown:: left (pd_test_1_all.cpp:1909) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1899 :emphasize-lines: 11 if (empty.size() != 0) { std::cout << "[FAIL] : in test_constructors() : default constructor size" << std::endl; return; } if (empty.closed() != pandas::IntervalClosed::Right) { std::cout << "[FAIL] : in test_constructors() : default closure" << std::endl; return; } // Constructor from left/right arrays numpy::NDArray left(std::vector{3}); numpy::NDArray right(std::vector{3}); left.setElementAt({0}, 0.0); right.setElementAt({0}, 1.0); left.setElementAt({1}, 1.0); right.setElementAt({1}, 2.0); left.setElementAt({2}, 2.0); right.setElementAt({2}, 3.0); pandas::IntervalArrayFloat64 arr1(left, right); if (arr1.size() != 3) { std::cout << "[FAIL] : in test_constructors() : array size" << std::endl; return; } .. _example-intervalindex-length-28: .. dropdown:: length (pd_test_1_all.cpp:2137) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2127 :emphasize-lines: 11 auto mid0 = mid_arr[0]; auto mid1 = mid_arr[1]; auto mid2 = mid_arr[2]; if (!mid0.has_value() || std::abs(mid0.value() - 1.0) > 1e-10 || !mid1.has_value() || std::abs(mid1.value() - 3.5) > 1e-10 || !mid2.has_value() || std::abs(mid2.value() - 7.5) > 1e-10) { std::cout << "[FAIL] : in test_left_right_mid_length() : mid()" << std::endl; return; } // Test length() auto len_arr = arr.length(); if (len_arr.getElementAt({0}) != 2.0 || len_arr.getElementAt({1}) != 3.0 || len_arr.getElementAt({2}) != 5.0) { std::cout << "[FAIL] : in test_left_right_mid_length() : length()" << std::endl; return; } std::cout << "-> tests passed" << std::endl; } .. _example-intervalindex-searchsorted-29: .. dropdown:: searchsorted (pd_test_1_all.cpp:18958) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 18948 :emphasize-lines: 11 // ========================================================================= // Search Tests // ========================================================================= void pd_test_range_index_searchsorted() { std::cout << "========= searchsorted ================================ "; pandas::RangeIndex ri(0, 10, 2); // [0, 2, 4, 6, 8] bool passed = (ri.searchsorted(4, "left") == 2 && ri.searchsorted(4, "right") == 3 && ri.searchsorted(3, "left") == 2 && // 3 would go between 2 and 4 ri.searchsorted(-1, "left") == 0 && // Before all ri.searchsorted(10, "left") == 5); // After all if (!passed) { std::cout << " [FAIL] : searchsorted" << std::endl; throw std::runtime_error("pd_test_range_index_searchsorted failed"); } .. _example-intervalindex-to_frame-30: .. dropdown:: to_frame (pd_test_3_all.cpp:4931) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 4921 :emphasize-lines: 11 size_t usage = mi.memory_usage(true); if (usage == 0) { throw std::runtime_error("memory_usage() should return > 0"); } std::cout << " -> tests passed" << std::endl; } void pd_test_3_all_multiindex_to_frame() { std::cout << "========= MultiIndex.to_frame() ======================="; std::vector> arrays = {{"a", "b"}, {"x", "y"}}; std::vector> names = {"first", "second"}; pandas::MultiIndex mi = pandas::MultiIndex::from_arrays(arrays, names); auto frame = mi.to_frame(); if (frame.find("first") == frame.end() || frame.find("second") == frame.end()) { throw std::runtime_error("to_frame() missing columns"); } .. _example-intervalindex-transpose-31: .. dropdown:: transpose (pd_test_1_all.cpp:16648) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 16638 :emphasize-lines: 11 std::cout << " [FAIL] : in pd_test_ndframe_transpose() : T_() size" << std::endl; throw std::runtime_error("pd_test_ndframe_transpose failed: T_() size"); } passed = transposed[0] == 1 && transposed[1] == 2 && transposed[2] == 3; if (!passed) { std::cout << " [FAIL] : in pd_test_ndframe_transpose() : T_() values" << std::endl; throw std::runtime_error("pd_test_ndframe_transpose failed: T_() values"); } // Test transpose() alias auto transposed2 = s.transpose(); passed = transposed2.size() == s.size(); if (!passed) { std::cout << " [FAIL] : in pd_test_ndframe_transpose() : transpose() size" << std::endl; throw std::runtime_error("pd_test_ndframe_transpose failed: transpose() size"); } std::cout << " -> tests passed" << std::endl; } .. _example-intervalindex-join-32: .. dropdown:: join (pd_test_1_all.cpp:12353) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 12343 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } void pd_test_index_join() { std::cout << "========= join ========================================"; pandas::Index idx1{1, 2, 3}; pandas::Index idx2{2, 3, 4}; auto [inner_joined, left_idx, right_idx] = idx1.join(idx2, "inner"); bool passed = (inner_joined.size() == 2); // {2, 3} auto [outer_joined, ol_idx, or_idx] = idx1.join(idx2, "outer"); passed = passed && (outer_joined.size() == 4); // {1, 2, 3, 4} if (!passed) { std::cout << " [FAIL] : in pd_test_index_join() : join failed" << std::endl; throw std::runtime_error("pd_test_index_join failed"); } .. _example-intervalindex-asof-33: .. dropdown:: asof (pd_test_2_all.cpp:366) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 356 :emphasize-lines: 11 std::cout << "====================================== [OK] pd_test_add_prefix test suite ========================== " << std::endl; return 0; } } // namespace dataframe_tests // ------------------- pd_test_add_prefix.cpp (end) ----------------------------- // ------------------- pd_test_asof.cpp (start) ----------------------------- // dataframe_tests/pd_test_asof.cpp // Test for DataFrame.asof() method #include #include #include #include #include "../pandas/pd_dataframe.h" // CRITICAL: No using namespace directives namespace dataframe_tests { .. _example-intervalindex-asof_locs-34: .. dropdown:: asof_locs (pd_test_3_all.cpp:3557) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3547 :emphasize-lines: 11 throw std::runtime_error("all() should be true for empty index"); } if (empty_idx.any()) { throw std::runtime_error("any() should be false for empty index"); } std::cout << " -> tests passed" << std::endl; } void pd_test_3_all_index_asof() { std::cout << "========= Index.asof()/asof_locs() ================="; // Test with monotonically increasing index pandas::Index idx({10, 20, 30, 40, 50}); // Exact match auto result = idx.asof(30); if (!result.has_value() || result.value() != 30) { throw std::runtime_error("asof() exact match should return 30"); } .. _example-intervalindex-diff-35: .. dropdown:: diff (pd_test_1_all.cpp:5171) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 5161 :emphasize-lines: 11 } void pd_test_arithmetic_dataframe_diff_shift() { std::cout << "========= DataFrame diff/shift =================="; std::map> data; data["A"] = {1.0, 3.0, 6.0, 10.0}; pandas::DataFrame df(data); // diff: [NaN, 2, 3, 4] auto d = df.diff(); std::string val = d["A"].get_value_str(1); bool passed = std::abs(std::stod(val) - 2.0) < 0.001; if (!passed) { std::cout << " [FAIL] : in pd_test_arithmetic_dataframe_diff_shift() : diff failed" << std::endl; throw std::runtime_error("pd_test_arithmetic_dataframe_diff_shift failed: diff failed"); } // First element should be NaN val = d["A"].get_value_str(0); passed = std::isnan(std::stod(val)); .. _example-intervalindex-shift-36: .. dropdown:: shift (pd_test_1_all.cpp:5188) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 5178 :emphasize-lines: 11 // First element should be NaN val = d["A"].get_value_str(0); passed = std::isnan(std::stod(val)); if (!passed) { std::cout << " [FAIL] : in pd_test_arithmetic_dataframe_diff_shift() : diff NaN failed" << std::endl; throw std::runtime_error("pd_test_arithmetic_dataframe_diff_shift failed: diff NaN failed"); } // shift: [NaN, 1, 3, 6] auto s = df.shift(); val = s["A"].get_value_str(1); passed = std::abs(std::stod(val) - 1.0) < 0.001; if (!passed) { std::cout << " [FAIL] : in pd_test_arithmetic_dataframe_diff_shift() : shift failed" << std::endl; throw std::runtime_error("pd_test_arithmetic_dataframe_diff_shift failed: shift failed"); } std::cout << " -> tests passed" << std::endl; } .. _example-intervalindex-to_flat_index-37: .. dropdown:: to_flat_index (pd_test_1_all.cpp:14733) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 14723 :emphasize-lines: 11 void pd_test_multiindex_to_flat_index() { std::cout << "========= to_flat_index =============================== "; std::vector> arrays = { {"a", "b"}, {"x", "y"} }; pandas::MultiIndex mi = pandas::MultiIndex::from_arrays(arrays); auto flat = mi.to_flat_index(); bool passed = (flat.size() == 2 && flat[0][0] == "a" && flat[0][1] == "x" && flat[1][0] == "b" && flat[1][1] == "y"); if (!passed) { std::cout << " [FAIL] : to_flat_index incorrect" << std::endl; throw std::runtime_error("pd_test_multiindex_to_flat_index failed"); } .. _example-intervalindex-to_numpy-38: .. dropdown:: to_numpy (pd_test_1_all.cpp:16764) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 16754 :emphasize-lines: 11 // ===================================================================== // to_numpy Tests // ===================================================================== void pd_test_ndframe_to_numpy() { std::cout << "========= to_numpy =============================================" << std::endl; pandas::Series s({10, 20, 30}); auto arr = s.to_numpy(); bool passed = arr.getSize() == 3; if (!passed) { std::cout << " [FAIL] : in pd_test_ndframe_to_numpy() : size" << std::endl; throw std::runtime_error("pd_test_ndframe_to_numpy failed: size"); } passed = arr.getElementAt({0}) == 10 && arr.getElementAt({1}) == 20 && arr.getElementAt({2}) == 30; if (!passed) { std::cout << " [FAIL] : in pd_test_ndframe_to_numpy() : values" << std::endl; .. _example-intervalindex-to_series-39: .. dropdown:: to_series (pd_test_3_all.cpp:5788) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 5778 :emphasize-lines: 11 throw std::runtime_error("to_frame use_index should be false when index=false"); } if (frame3.column_name != "0") { throw std::runtime_error("to_frame column_name should be '0' when no name"); } std::cout << " -> tests passed" << std::endl; } void pd_test_3_all_period_index_to_series() { std::cout << "========= PeriodIndex.to_series() ====================="; pandas::PeriodIndex idx = make_period_index({1, 2, 3}, "M").rename("periods"); // Test to_series() with default parameters pandas::PeriodIndex::SeriesData series = idx.to_series(); // values should have same size if (series.values.size() != 3) { throw std::runtime_error("to_series values size should be 3"); } .. _example-intervalindex-to_string-40: .. dropdown:: to_string (pd_test_1_all.cpp:2693) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2683 :emphasize-lines: 11 pandas::PeriodArray arr_m(std::vector{ "2020-01", "NaT", "2025-06" }, "M"); // Year auto years = arr_m.year(); auto y0 = years[0]; if (!y0.has_value() || y0.value() != 2020) { std::cout << " [FAIL] : year[0] should be 2020, got " << (y0.has_value() ? std::to_string(y0.value()) : "NA") << std::endl; throw std::runtime_error("pd_test_period_array_year_month_quarter failed: year[0]"); } auto y1 = years[1]; if (y1.has_value()) { std::cout << " [FAIL] : year[1] should be NA (NaT)" << std::endl; throw std::runtime_error("pd_test_period_array_year_month_quarter failed: year[1] should be NA"); } auto y2 = years[2]; .. _example-intervalindex-to_tuples-41: .. dropdown:: to_tuples (pd_test_1_all.cpp:13037) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 13027 :emphasize-lines: 11 } std::cout << " -> tests passed" << std::endl; } void pd_test_interval_index_to_tuples() { std::cout << "========= to_tuples ========================="; auto idx = pandas::IntervalIndex64::from_breaks({0, 1, 2, 3}); auto tuples = idx.to_tuples(); bool passed = (tuples.size() == 3 && tuples[0].has_value() && tuples[0]->first == 0 && tuples[0]->second == 1 && tuples[1].has_value() && tuples[1]->first == 1 && tuples[1]->second == 2 && tuples[2].has_value() && tuples[2]->first == 2 && tuples[2]->second == 3); if (!passed) { std::cout << " [FAIL] : in pd_test_interval_index_to_tuples() : check failed" << std::endl; throw std::runtime_error("pd_test_interval_index_to_tuples failed"); } .. _example-intervalindex-tolist-42: .. dropdown:: tolist (pd_test_3_all.cpp:2300) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2290 :emphasize-lines: 11 threw = true; } if (!threw) { throw std::runtime_error("swapaxes should throw for invalid axes"); } std::cout << " -> tests passed" << std::endl; } void pd_test_3_all_categorical_to_list() { std::cout << "========= CategoricalArray.to_list()/tolist() ========="; std::vector> values = {"a", "b", std::nullopt, "c"}; pandas::CategoricalArray arr(values); auto list = arr.to_list(); if (list.size() != 4 || *list[0] != "a" || *list[1] != "b" || list[2].has_value() || *list[3] != "c") { throw std::runtime_error("to_list failed"); } .. _example-intervalindex-astype-43: .. dropdown:: astype (pd_test_1_all.cpp:21292) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21282 :emphasize-lines: 11 std::cout << "========= astype all columns to float64 ============="; // Create DataFrame with int64 columns std::map> data; data["A"] = {1, 2, 3, 4, 5}; data["B"] = {10, 20, 30, 40, 50}; pandas::DataFrame df(data); // Convert all columns to float64 pandas::DataFrame df_float = df.astype("float64"); // Verify dtype changed pandas::Series dtypes = df_float.dtypes(); bool passed = true; if (dtypes[static_cast(0)] != "float64") { std::cout << " [FAIL] : in pd_test_astype_all_columns_to_float64() : column A dtype is " << dtypes[static_cast(0)] << ", expected float64" << std::endl; passed = false; } if (dtypes[static_cast(1)] != "float64") { .. _example-intervalindex-copy-44: .. dropdown:: copy (pd_test_1_all.cpp:5798) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 5788 :emphasize-lines: 11 // ============================================================================ // Copy/Rename Tests // ============================================================================ void pd_test_categorical_index_copy() { std::cout << "========= copy ========================================"; pandas::CategoricalArray arr({"a", "b", "c"}); pandas::CategoricalIndex idx(arr, "original"); pandas::CategoricalIndex copied = idx.copy(); bool passed = (copied.size() == idx.size() && copied.name() == idx.name() && copied.categories() == idx.categories() && copied.ordered() == idx.ordered()); if (!passed) { std::cout << " [FAIL] : in pd_test_categorical_index_copy()" << std::endl; throw std::runtime_error("pd_test_categorical_index_copy failed"); } std::cout << " -> tests passed" << std::endl; } .. _example-intervalindex-infer_objects-45: .. dropdown:: infer_objects (pd_test_1_all.cpp:27595) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 27585 :emphasize-lines: 11 // Create DataFrame with string column containing integers std::map> data; data["A"] = {"1", "2", "3", "4", "5"}; pandas::DataFrame df(data); // Before inference, dtype should be string/object std::string before_dtype = df["A"].dtype_name(); // Apply infer_objects pandas::DataFrame result = df.infer_objects(); // After inference, dtype should be int64 std::string after_dtype = result["A"].dtype_name(); bool passed = (after_dtype == "int64"); if (!passed) { std::cout << " [FAIL] : in pd_test_infer_objects_integer_column() : expected int64, got " << after_dtype << std::endl; throw std::runtime_error("pd_test_infer_objects_integer_column failed"); } .. _example-intervalindex-view-46: .. dropdown:: view (pd_test_3_all.cpp:2147) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2137 :emphasize-lines: 11 throw std::runtime_error("memory_usage shallow too small"); } if (deep < shallow) { throw std::runtime_error("memory_usage deep should be >= shallow"); } std::cout << " -> tests passed" << std::endl; } void pd_test_3_all_categorical_ravel_view() { std::cout << "========= CategoricalArray.ravel()/view() ============="; std::vector> values = {"a", "b", "c"}; pandas::CategoricalArray arr(values); auto raveled = arr.ravel(); if (raveled.size() != 3 || !raveled.equals(arr)) { throw std::runtime_error("ravel failed"); } auto viewed = arr.view(); .. _example-intervalindex-duplicated-47: .. dropdown:: duplicated (pd_test_1_all.cpp:10583) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 10573 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } void pd_test_extension_index_duplicated() { std::cout << "========= duplicated ========================="; pandas::CategoricalArray arr({"a", "b", "a", "c", "a"}); pandas::CategoricalIndex idx(arr); auto dup_mask = idx.duplicated("first"); bool passed = (dup_mask.getElementAt({0}) == false && dup_mask.getElementAt({1}) == false && dup_mask.getElementAt({2}) == true && dup_mask.getElementAt({3}) == false && dup_mask.getElementAt({4}) == true); if (!passed) { std::cout << " [FAIL] : in pd_test_extension_index_duplicated() : duplicated check failed" << std::endl; throw std::runtime_error("pd_test_extension_index_duplicated failed"); } .. _example-intervalindex-union_-48: .. dropdown:: union_ (pd_test_1_all.cpp:10694) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 10684 :emphasize-lines: 11 std::cout << "========= union ========================="; // Use same categories for both arrays std::vector cats = {"a", "b", "c", "d", "e"}; pandas::CategoricalArray arr1({"a", "b", "c"}, cats); pandas::CategoricalIndex idx1(arr1); pandas::CategoricalArray arr2({"b", "c", "d", "e"}, cats); pandas::CategoricalIndex idx2(arr2); auto uni = idx1.union_(idx2); bool passed = (uni.size() == 5 && uni.contains("a") && uni.contains("b") && uni.contains("c") && uni.contains("d") && uni.contains("e")); if (!passed) { std::cout << " [FAIL] : in pd_test_extension_index_union() : union check failed" << std::endl; throw std::runtime_error("pd_test_extension_index_union failed"); } std::cout << " -> tests passed" << std::endl; .. _example-intervalindex-unique-49: .. dropdown:: unique (pd_test_1_all.cpp:1345) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1335 :emphasize-lines: 11 pandas::DatetimeArray arr(std::vector{ "2023-01-01", "2023-06-15", "2023-01-01", "NaT", "2023-06-15", "NaT" }); // unique auto uniq = arr.unique(); // Should have: NaT, 2023-01-01, 2023-06-15 (3 unique values) if (uniq.size() != 3) { std::cout << " [FAIL] : unique size should be 3, got " << uniq.size() << std::endl; throw std::runtime_error("pd_test_datetime_array_unique failed: size"); } // factorize auto [codes, uniques] = arr.factorize(); // Codes for NaT should be -1 if (codes.getElementAt({3}) != -1) { .. _example-intervalindex-is_-50: .. dropdown:: is_ (pd_test_3_all.cpp:3972) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3962 :emphasize-lines: 11 // For typed Index, this is a no-op if (result.size() != 5) { throw std::runtime_error("infer_objects size should be 5"); } std::cout << " -> tests passed" << std::endl; } void pd_test_3_all_index_is_() { std::cout << "========= Index.is_() =============================="; pandas::Index idx1({1, 2, 3, 4, 5}); pandas::Index idx2({1, 2, 3, 4, 5}); // Different object // Different objects should not be the same if (idx1.is_(idx2)) { throw std::runtime_error("different objects should not be is_() equal"); } // Same object should be the same .. _example-intervalindex-is_boolean-51: .. dropdown:: is_boolean (pd_test_3_all.cpp:3290) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3280 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } void pd_test_3_all_datetime_index_type_checks() { std::cout << "========= DatetimeIndex type checks ======================"; pandas::DatetimeIndex idx = pandas::date_range("2024-01-01", "2024-01-05", std::nullopt, "D"); // Type check methods if (idx.is_boolean()) { throw std::runtime_error("is_boolean() should be false"); } if (idx.is_categorical()) { throw std::runtime_error("is_categorical() should be false"); } if (idx.is_floating()) { throw std::runtime_error("is_floating() should be false"); } if (idx.is_integer()) { throw std::runtime_error("is_integer() should be false"); .. _example-intervalindex-is_categorical-52: .. dropdown:: is_categorical (pd_test_3_all.cpp:3293) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3283 :emphasize-lines: 11 void pd_test_3_all_datetime_index_type_checks() { std::cout << "========= DatetimeIndex type checks ======================"; pandas::DatetimeIndex idx = pandas::date_range("2024-01-01", "2024-01-05", std::nullopt, "D"); // Type check methods if (idx.is_boolean()) { throw std::runtime_error("is_boolean() should be false"); } if (idx.is_categorical()) { throw std::runtime_error("is_categorical() should be false"); } if (idx.is_floating()) { throw std::runtime_error("is_floating() should be false"); } if (idx.is_integer()) { throw std::runtime_error("is_integer() should be false"); } if (idx.is_interval()) { throw std::runtime_error("is_interval() should be false"); .. _example-intervalindex-is_empty-53: .. dropdown:: is_empty (pd_test_1_all.cpp:2164) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2154 :emphasize-lines: 11 // Test with right-closed intervals (a, b] std::vector> tuples = { {0.0, 1.0}, // Not empty {1.0, 1.0}, // Empty (1, 1] has no points {2.0, 2.0}, // Empty {2.0, 3.0} // Not empty }; auto arr_right = pandas::IntervalArrayFloat64::from_tuples(tuples, pandas::IntervalClosed::Right); auto empty_right = arr_right.is_empty(); if (empty_right[0].value_or(true) != false || empty_right[1].value_or(false) != true || empty_right[2].value_or(false) != true || empty_right[3].value_or(true) != false) { std::cout << "[FAIL] : in test_is_empty() : right-closed" << std::endl; return; } // Test with both-closed intervals [a, b] - [1, 1] is NOT empty .. _example-intervalindex-is_floating-54: .. dropdown:: is_floating (pd_test_3_all.cpp:622) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 612 :emphasize-lines: 11 // Test with integer index pandas::IndexDtype int_dtype; if (!int_dtype.is_numeric()) { std::cout << " [FAIL] : in pd_test_3_all_index_dtype_checks() : int should be numeric" << std::endl; throw std::runtime_error("pd_test_3_all_index_dtype_checks failed: int is_numeric"); } if (!int_dtype.is_integer()) { std::cout << " [FAIL] : in pd_test_3_all_index_dtype_checks() : int should be integer" << std::endl; throw std::runtime_error("pd_test_3_all_index_dtype_checks failed: int is_integer"); } if (int_dtype.is_floating()) { std::cout << " [FAIL] : in pd_test_3_all_index_dtype_checks() : int should not be floating" << std::endl; throw std::runtime_error("pd_test_3_all_index_dtype_checks failed: int is_floating"); } if (int_dtype.is_object()) { std::cout << " [FAIL] : in pd_test_3_all_index_dtype_checks() : int should not be object" << std::endl; throw std::runtime_error("pd_test_3_all_index_dtype_checks failed: int is_object"); } // Test with float index pandas::IndexDtype float_dtype; .. _example-intervalindex-is_integer-55: .. dropdown:: is_integer (pd_test_3_all.cpp:618) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 608 :emphasize-lines: 11 void pd_test_3_all_index_dtype_checks() { std::cout << "========= IndexDtype.is_numeric/integer/floating/object() "; // Test with integer index pandas::IndexDtype int_dtype; if (!int_dtype.is_numeric()) { std::cout << " [FAIL] : in pd_test_3_all_index_dtype_checks() : int should be numeric" << std::endl; throw std::runtime_error("pd_test_3_all_index_dtype_checks failed: int is_numeric"); } if (!int_dtype.is_integer()) { std::cout << " [FAIL] : in pd_test_3_all_index_dtype_checks() : int should be integer" << std::endl; throw std::runtime_error("pd_test_3_all_index_dtype_checks failed: int is_integer"); } if (int_dtype.is_floating()) { std::cout << " [FAIL] : in pd_test_3_all_index_dtype_checks() : int should not be floating" << std::endl; throw std::runtime_error("pd_test_3_all_index_dtype_checks failed: int is_floating"); } if (int_dtype.is_object()) { std::cout << " [FAIL] : in pd_test_3_all_index_dtype_checks() : int should not be object" << std::endl; throw std::runtime_error("pd_test_3_all_index_dtype_checks failed: int is_object"); .. _example-intervalindex-is_interval-56: .. dropdown:: is_interval (pd_test_3_all.cpp:3302) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3292 :emphasize-lines: 11 } if (idx.is_categorical()) { throw std::runtime_error("is_categorical() should be false"); } if (idx.is_floating()) { throw std::runtime_error("is_floating() should be false"); } if (idx.is_integer()) { throw std::runtime_error("is_integer() should be false"); } if (idx.is_interval()) { throw std::runtime_error("is_interval() should be false"); } if (idx.is_numeric()) { throw std::runtime_error("is_numeric() should be false"); } if (idx.is_object()) { throw std::runtime_error("is_object() should be false"); } if (idx.holds_integer()) { throw std::runtime_error("holds_integer() should be false"); .. _example-intervalindex-is_left_closed-57: .. dropdown:: is_left_closed (pd_test_1_all.cpp:12830) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 12820 :emphasize-lines: 11 } void pd_test_interval_index_is_left_right_closed() { std::cout << "========= is_left_closed/is_right_closed ========================="; auto idx_right = pandas::IntervalIndex64::from_breaks({0, 1, 2}, pandas::IntervalClosed::Right); auto idx_left = pandas::IntervalIndex64::from_breaks({0, 1, 2}, pandas::IntervalClosed::Left); auto idx_both = pandas::IntervalIndex64::from_breaks({0, 1, 2}, pandas::IntervalClosed::Both); auto idx_neither = pandas::IntervalIndex64::from_breaks({0, 1, 2}, pandas::IntervalClosed::Neither); bool passed = (!idx_right.is_left_closed() && idx_right.is_right_closed() && idx_left.is_left_closed() && !idx_left.is_right_closed() && idx_both.is_left_closed() && idx_both.is_right_closed() && !idx_neither.is_left_closed() && !idx_neither.is_right_closed()); if (!passed) { std::cout << " [FAIL] : in pd_test_interval_index_is_left_right_closed() : check failed" << std::endl; throw std::runtime_error("pd_test_interval_index_is_left_right_closed failed"); } std::cout << " -> tests passed" << std::endl; } .. _example-intervalindex-is_non_overlapping_monotonic-58: .. dropdown:: is_non_overlapping_monotonic (pd_test_1_all.cpp:2457) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2447 :emphasize-lines: 11 // ============================================================================ // Test: is_non_overlapping_monotonic // ============================================================================ void test_is_non_overlapping_monotonic() { std::cout << "========= IntervalArray: is_non_overlapping_monotonic ======================= "; // Monotonic, non-overlapping std::vector breaks1 = {0.0, 1.0, 2.0, 3.0}; auto arr1 = pandas::IntervalArrayFloat64::from_breaks(breaks1, pandas::IntervalClosed::Right); if (!arr1.is_non_overlapping_monotonic()) { std::cout << "[FAIL] : in test_is_non_overlapping_monotonic() : should be true for breaks" << std::endl; return; } // Non-monotonic (out of order) std::vector> tuples2 = { {2.0, 3.0}, {0.0, 1.0}, {1.0, 2.0} }; auto arr2 = pandas::IntervalArrayFloat64::from_tuples(tuples2); if (arr2.is_non_overlapping_monotonic()) { .. _example-intervalindex-is_numeric-59: .. dropdown:: is_numeric (pd_test_3_all.cpp:614) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 604 :emphasize-lines: 11 // ============================================================================ // Category 4: Index Type Checking (IndexDtype) // ============================================================================ void pd_test_3_all_index_dtype_checks() { std::cout << "========= IndexDtype.is_numeric/integer/floating/object() "; // Test with integer index pandas::IndexDtype int_dtype; if (!int_dtype.is_numeric()) { std::cout << " [FAIL] : in pd_test_3_all_index_dtype_checks() : int should be numeric" << std::endl; throw std::runtime_error("pd_test_3_all_index_dtype_checks failed: int is_numeric"); } if (!int_dtype.is_integer()) { std::cout << " [FAIL] : in pd_test_3_all_index_dtype_checks() : int should be integer" << std::endl; throw std::runtime_error("pd_test_3_all_index_dtype_checks failed: int is_integer"); } if (int_dtype.is_floating()) { std::cout << " [FAIL] : in pd_test_3_all_index_dtype_checks() : int should not be floating" << std::endl; throw std::runtime_error("pd_test_3_all_index_dtype_checks failed: int is_floating"); .. _example-intervalindex-is_object-60: .. dropdown:: is_object (pd_test_3_all.cpp:626) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 616 :emphasize-lines: 11 throw std::runtime_error("pd_test_3_all_index_dtype_checks failed: int is_numeric"); } if (!int_dtype.is_integer()) { std::cout << " [FAIL] : in pd_test_3_all_index_dtype_checks() : int should be integer" << std::endl; throw std::runtime_error("pd_test_3_all_index_dtype_checks failed: int is_integer"); } if (int_dtype.is_floating()) { std::cout << " [FAIL] : in pd_test_3_all_index_dtype_checks() : int should not be floating" << std::endl; throw std::runtime_error("pd_test_3_all_index_dtype_checks failed: int is_floating"); } if (int_dtype.is_object()) { std::cout << " [FAIL] : in pd_test_3_all_index_dtype_checks() : int should not be object" << std::endl; throw std::runtime_error("pd_test_3_all_index_dtype_checks failed: int is_object"); } // Test with float index pandas::IndexDtype float_dtype; if (!float_dtype.is_numeric()) { std::cout << " [FAIL] : in pd_test_3_all_index_dtype_checks() : float should be numeric" << std::endl; throw std::runtime_error("pd_test_3_all_index_dtype_checks failed: float is_numeric"); } .. _example-intervalindex-is_overlapping-61: .. dropdown:: is_overlapping (pd_test_1_all.cpp:12891) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 12881 :emphasize-lines: 11 std::cout << "========= is_overlapping ========================="; // Non-overlapping intervals auto idx1 = pandas::IntervalIndex64::from_breaks({0, 1, 2, 3}); // Overlapping intervals: [0,5], [3,8] std::vector left_vals = {0, 3}; std::vector right_vals = {5, 8}; auto idx2 = pandas::IntervalIndex64::from_arrays(left_vals, right_vals, pandas::IntervalClosed::Both); bool passed = (!idx1.is_overlapping() && idx2.is_overlapping()); if (!passed) { std::cout << " [FAIL] : in pd_test_interval_index_is_overlapping() : check failed" << std::endl; throw std::runtime_error("pd_test_interval_index_is_overlapping failed"); } std::cout << " -> tests passed" << std::endl; } void pd_test_interval_index_is_non_overlapping_monotonic() { std::cout << "========= is_non_overlapping_monotonic ========================="; .. _example-intervalindex-is_right_closed-62: .. dropdown:: is_right_closed (pd_test_1_all.cpp:12830) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 12820 :emphasize-lines: 11 } void pd_test_interval_index_is_left_right_closed() { std::cout << "========= is_left_closed/is_right_closed ========================="; auto idx_right = pandas::IntervalIndex64::from_breaks({0, 1, 2}, pandas::IntervalClosed::Right); auto idx_left = pandas::IntervalIndex64::from_breaks({0, 1, 2}, pandas::IntervalClosed::Left); auto idx_both = pandas::IntervalIndex64::from_breaks({0, 1, 2}, pandas::IntervalClosed::Both); auto idx_neither = pandas::IntervalIndex64::from_breaks({0, 1, 2}, pandas::IntervalClosed::Neither); bool passed = (!idx_right.is_left_closed() && idx_right.is_right_closed() && idx_left.is_left_closed() && !idx_left.is_right_closed() && idx_both.is_left_closed() && idx_both.is_right_closed() && !idx_neither.is_left_closed() && !idx_neither.is_right_closed()); if (!passed) { std::cout << " [FAIL] : in pd_test_interval_index_is_left_right_closed() : check failed" << std::endl; throw std::runtime_error("pd_test_interval_index_is_left_right_closed failed"); } std::cout << " -> tests passed" << std::endl; } .. _example-intervalindex-all-63: .. dropdown:: all (pd_test_1_all.cpp:247) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 237 :emphasize-lines: 11 pandas::BooleanArray has_true({ std::optional(false), std::optional(true) }); any_result = has_true.any(); if (!any_result.has_value() || !any_result.value()) { std::cout << " [FAIL] : in pd_test_boolean_array_reductions() : any() with True" << std::endl; throw std::runtime_error("pd_test_boolean_array_reductions failed: any() with True"); } // Test all() pandas::BooleanArray all_true({ std::optional(true), std::optional(true) }); auto all_result = all_true.all(); if (!all_result.has_value() || !all_result.value()) { std::cout << " [FAIL] : in pd_test_boolean_array_reductions() : all() of all True" << std::endl; throw std::runtime_error("pd_test_boolean_array_reductions failed: all() all True"); } .. _example-intervalindex-any-64: .. dropdown:: any (pd_test_1_all.cpp:226) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 216 :emphasize-lines: 11 std::cout << " [FAIL] : in pd_test_boolean_array_kleene_not() : ~NA should be NA" << std::endl; throw std::runtime_error("pd_test_boolean_array_kleene_not failed: ~NA"); } std::cout << " -> tests passed" << std::endl; } void pd_test_boolean_array_reductions() { std::cout << "========= BooleanArray: reductions ======================= "; // Test any() pandas::BooleanArray all_false({ std::optional(false), std::optional(false) }); auto any_result = all_false.any(); if (!any_result.has_value() || any_result.value()) { std::cout << " [FAIL] : in pd_test_boolean_array_reductions() : any() of all False" << std::endl; throw std::runtime_error("pd_test_boolean_array_reductions failed: any() all False"); } .. _example-intervalindex-argmax-65: .. dropdown:: argmax (pd_test_1_all.cpp:1323) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1313 :emphasize-lines: 11 } // argmin auto min_idx = arr.argmin(); if (!min_idx.has_value() || min_idx.value() != 2) { std::cout << " [FAIL] : argmin should be 2 (2023-01-01)" << std::endl; throw std::runtime_error("pd_test_datetime_array_sorting failed: argmin"); } // argmax auto max_idx = arr.argmax(); if (!max_idx.has_value() || max_idx.value() != 3) { std::cout << " [FAIL] : argmax should be 3 (2023-12-31)" << std::endl; throw std::runtime_error("pd_test_datetime_array_sorting failed: argmax"); } std::cout << " -> tests passed" << std::endl; } void pd_test_datetime_array_unique() { std::cout << "========= DatetimeArray: unique/factorize ======================= "; .. _example-intervalindex-argmin-66: .. dropdown:: argmin (pd_test_1_all.cpp:1316) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1306 :emphasize-lines: 11 if (indices.getElementAt({0}) != 2) { std::cout << " [FAIL] : argsort: first should be index 2 (2023-01-01)" << std::endl; throw std::runtime_error("pd_test_datetime_array_sorting failed: argsort first"); } if (indices.getElementAt({3}) != 1) { std::cout << " [FAIL] : argsort: last should be index 1 (NaT)" << std::endl; throw std::runtime_error("pd_test_datetime_array_sorting failed: NaT position"); } // argmin auto min_idx = arr.argmin(); if (!min_idx.has_value() || min_idx.value() != 2) { std::cout << " [FAIL] : argmin should be 2 (2023-01-01)" << std::endl; throw std::runtime_error("pd_test_datetime_array_sorting failed: argmin"); } // argmax auto max_idx = arr.argmax(); if (!max_idx.has_value() || max_idx.value() != 3) { std::cout << " [FAIL] : argmax should be 3 (2023-12-31)" << std::endl; throw std::runtime_error("pd_test_datetime_array_sorting failed: argmax"); .. _example-intervalindex-arr-67: .. dropdown:: arr (pd_test_1_all.cpp:45) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 35 :emphasize-lines: 11 std::cout << " [FAIL] : in pd_test_boolean_array_constructors() : initializer_list size != 4" << std::endl; throw std::runtime_error("pd_test_boolean_array_constructors failed: initializer_list size != 4"); } std::cout << " -> tests passed" << std::endl; } void pd_test_boolean_array_na_handling() { std::cout << "========= BooleanArray: NA handling ======================= "; pandas::BooleanArray arr({ std::optional(true), std::nullopt, // NA at index 1 std::optional(false) }); if (!arr.is_na(1)) { std::cout << " [FAIL] : in pd_test_boolean_array_na_handling() : is_na(1) should be true" << std::endl; throw std::runtime_error("pd_test_boolean_array_na_handling failed: is_na(1) should be true"); } .. _example-intervalindex-arr-68: .. dropdown:: arr (pd_test_1_all.cpp:45) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 35 :emphasize-lines: 11 std::cout << " [FAIL] : in pd_test_boolean_array_constructors() : initializer_list size != 4" << std::endl; throw std::runtime_error("pd_test_boolean_array_constructors failed: initializer_list size != 4"); } std::cout << " -> tests passed" << std::endl; } void pd_test_boolean_array_na_handling() { std::cout << "========= BooleanArray: NA handling ======================= "; pandas::BooleanArray arr({ std::optional(true), std::nullopt, // NA at index 1 std::optional(false) }); if (!arr.is_na(1)) { std::cout << " [FAIL] : in pd_test_boolean_array_na_handling() : is_na(1) should be true" << std::endl; throw std::runtime_error("pd_test_boolean_array_na_handling failed: is_na(1) should be true"); } .. _example-intervalindex-clone-69: .. dropdown:: clone (pd_test_1_all.cpp:5776) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 5766 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } void pd_test_categorical_index_clone() { std::cout << "========= clone ======================================="; pandas::CategoricalArray arr({"p", "q", "r"}); pandas::CategoricalIndex idx(arr, "original"); std::unique_ptr cloned = idx.clone(); bool passed = (cloned != nullptr && cloned->size() == idx.size() && cloned->name() == idx.name()); if (!passed) { std::cout << " [FAIL] : in pd_test_categorical_index_clone()" << std::endl; throw std::runtime_error("pd_test_categorical_index_clone failed"); } std::cout << " -> tests passed" << std::endl; } .. _example-intervalindex-closed-70: .. dropdown:: closed (pd_test_1_all.cpp:1903) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1893 :emphasize-lines: 11 // ============================================================================ void test_constructors() { std::cout << "========= IntervalArray: constructors ======================= "; // Default constructor pandas::IntervalArrayFloat64 empty; if (empty.size() != 0) { std::cout << "[FAIL] : in test_constructors() : default constructor size" << std::endl; return; } if (empty.closed() != pandas::IntervalClosed::Right) { std::cout << "[FAIL] : in test_constructors() : default closure" << std::endl; return; } // Constructor from left/right arrays numpy::NDArray left(std::vector{3}); numpy::NDArray right(std::vector{3}); left.setElementAt({0}, 0.0); right.setElementAt({0}, 1.0); left.setElementAt({1}, 1.0); right.setElementAt({1}, 2.0); left.setElementAt({2}, 2.0); right.setElementAt({2}, 3.0); .. _example-intervalindex-closed_string-71: .. dropdown:: closed_string (pd_test_1_all.cpp:12813) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 12803 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } void pd_test_interval_index_closed_string() { std::cout << "========= closed_string ========================="; auto idx_right = pandas::IntervalIndex64::from_breaks({0, 1, 2}, pandas::IntervalClosed::Right); auto idx_left = pandas::IntervalIndex64::from_breaks({0, 1, 2}, pandas::IntervalClosed::Left); bool passed = (idx_right.closed_string() == "right" && idx_left.closed_string() == "left"); if (!passed) { std::cout << " [FAIL] : in pd_test_interval_index_closed_string() : closed_string check failed" << std::endl; throw std::runtime_error("pd_test_interval_index_closed_string failed"); } std::cout << " -> tests passed" << std::endl; } void pd_test_interval_index_is_left_right_closed() { std::cout << "========= is_left_closed/is_right_closed ========================="; .. _example-intervalindex-contains-72: .. dropdown:: contains (pd_test_1_all.cpp:2200) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2190 :emphasize-lines: 11 // Test: contains method // ============================================================================ void test_contains() { std::cout << "========= IntervalArray: contains ======================= "; std::vector breaks = {0.0, 1.0, 2.0, 3.0}; // Right-closed intervals: (0, 1], (1, 2], (2, 3] auto arr_right = pandas::IntervalArrayFloat64::from_breaks(breaks, pandas::IntervalClosed::Right); // Test contains(1.0) - should be in interval 0 but not 1 (since 1 is exclusive on left of interval 1) auto contains_1 = arr_right.contains(1.0); // (0, 1] contains 1: yes, (1, 2] contains 1: no (open on left), (2, 3] contains 1: no if (contains_1[0].value_or(false) != true || contains_1[1].value_or(true) != false || contains_1[2].value_or(true) != false) { std::cout << "[FAIL] : in test_contains() : right-closed contains 1.0" << std::endl; return; } // Left-closed intervals: [0, 1), [1, 2), [2, 3) .. _example-intervalindex-contains-73: .. dropdown:: contains (pd_test_1_all.cpp:2200) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2190 :emphasize-lines: 11 // Test: contains method // ============================================================================ void test_contains() { std::cout << "========= IntervalArray: contains ======================= "; std::vector breaks = {0.0, 1.0, 2.0, 3.0}; // Right-closed intervals: (0, 1], (1, 2], (2, 3] auto arr_right = pandas::IntervalArrayFloat64::from_breaks(breaks, pandas::IntervalClosed::Right); // Test contains(1.0) - should be in interval 0 but not 1 (since 1 is exclusive on left of interval 1) auto contains_1 = arr_right.contains(1.0); // (0, 1] contains 1: yes, (1, 2] contains 1: no (open on left), (2, 3] contains 1: no if (contains_1[0].value_or(false) != true || contains_1[1].value_or(true) != false || contains_1[2].value_or(true) != false) { std::cout << "[FAIL] : in test_contains() : right-closed contains 1.0" << std::endl; return; } // Left-closed intervals: [0, 1), [1, 2), [2, 3) .. _example-intervalindex-delete_-74: .. dropdown:: delete_ (pd_test_1_all.cpp:10501) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 10491 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } void pd_test_extension_index_delete() { std::cout << "========= delete_ ========================="; pandas::CategoricalArray arr({"a", "b", "c", "d"}); pandas::CategoricalIndex idx(arr); auto deleted = idx.delete_(1); auto v0 = deleted[0]; auto v1 = deleted[1]; auto v2 = deleted[2]; bool passed = (deleted.size() == 3 && v0.has_value() && *v0 == "a" && v1.has_value() && *v1 == "c" && v2.has_value() && *v2 == "d"); if (!passed) { std::cout << " [FAIL] : in pd_test_extension_index_delete() : delete_ check failed" << std::endl; .. _example-intervalindex-delete_-75: .. dropdown:: delete_ (pd_test_1_all.cpp:10501) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 10491 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } void pd_test_extension_index_delete() { std::cout << "========= delete_ ========================="; pandas::CategoricalArray arr({"a", "b", "c", "d"}); pandas::CategoricalIndex idx(arr); auto deleted = idx.delete_(1); auto v0 = deleted[0]; auto v1 = deleted[1]; auto v2 = deleted[2]; bool passed = (deleted.size() == 3 && v0.has_value() && *v0 == "a" && v1.has_value() && *v1 == "c" && v2.has_value() && *v2 == "d"); if (!passed) { std::cout << " [FAIL] : in pd_test_extension_index_delete() : delete_ check failed" << std::endl; .. _example-intervalindex-dtype_name-76: .. dropdown:: dtype_name (pd_test_1_all.cpp:10104) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 10094 :emphasize-lines: 11 } void pd_test_extension_index_array_constructor() { std::cout << "========= array constructor ========================="; pandas::CategoricalArray arr({"apple", "banana", "apple", "cherry"}); pandas::CategoricalIndex idx(arr, "fruits"); bool passed = (idx.size() == 4 && !idx.empty() && idx.name().has_value() && *idx.name() == "fruits" && idx.dtype_name() == "category"); if (!passed) { std::cout << " [FAIL] : in pd_test_extension_index_array_constructor() : array constructor check failed" << std::endl; throw std::runtime_error("pd_test_extension_index_array_constructor failed"); } std::cout << " -> tests passed" << std::endl; } void pd_test_extension_index_copy_constructor() { std::cout << "========= copy constructor ========================="; .. _example-intervalindex-format-77: .. dropdown:: format (main.cpp:20) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 10 :emphasize-lines: 11 int main() { // Automatically log all output to temp/pd_test_output.log numpy::TestLogger logger("temp/pd_test_output.log"); int res = 0; int res1 = 0; std::string resS = ""; // call all the tests res1 = dataframe_tests::pd_test_main(); resS += std::format(" pd_test_main: {} errors\n", res1); res += res1; std::cout << "\n------------------------- main --------------------------------------------\n"; std::cout << std::endl << "All tests completed. Nb errors = " << res << std::endl; std::cout << "Details: \n" << resS; std::cout << "\n---------------------------------------------------------------------------\n"; return res; } .. _example-intervalindex-format_interval-78: .. dropdown:: format_interval (pd_test_3_all.cpp:24894) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 24884 :emphasize-lines: 11 namespace dataframe_tests_interval_type_inference { void pd_test_interval_type_inference_breaks_int() { std::cout << "========= interval_type_inference_breaks_int ======================= "; auto idx = pandas::IntervalIndex::from_breaks({0.0, 1.0, 2.0, 3.0}); if (idx.subtype_override() != "int64") throw std::runtime_error("expected subtype_override 'int64', got '" + idx.subtype_override() + "'"); std::string dtype = idx.dtype_name(); if (dtype.find("int64") == std::string::npos) throw std::runtime_error("expected dtype containing 'int64', got '" + dtype + "'"); std::string fmt = idx.format_interval(0); if (fmt.find('.') != std::string::npos) throw std::runtime_error("expected integer format without decimal, got '" + fmt + "'"); std::cout << " -> tests passed" << std::endl; } void pd_test_interval_type_inference_breaks_float() { std::cout << "========= interval_type_inference_breaks_float ===================== "; auto idx = pandas::IntervalIndex::from_breaks({0.0, 1.5, 3.0}); if (!idx.subtype_override().empty()) throw std::runtime_error("expected empty subtype_override, got '" + idx.subtype_override() + "'"); .. _example-intervalindex-holds_integer-79: .. dropdown:: holds_integer (pd_test_3_all.cpp:3311) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3301 :emphasize-lines: 11 } if (idx.is_interval()) { throw std::runtime_error("is_interval() should be false"); } if (idx.is_numeric()) { throw std::runtime_error("is_numeric() should be false"); } if (idx.is_object()) { throw std::runtime_error("is_object() should be false"); } if (idx.holds_integer()) { throw std::runtime_error("holds_integer() should be false"); } std::cout << " -> tests passed" << std::endl; } void pd_test_3_all_datetime_index_sort() { std::cout << "========= DatetimeIndex.sort_values() ===================="; pandas::DatetimeIndex idx = pandas::date_range("2024-01-01", "2024-01-05", std::nullopt, "D"); .. _example-intervalindex-inferred_type-80: .. dropdown:: inferred_type (pd_test_1_all.cpp:5270) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 5260 :emphasize-lines: 11 } void pd_test_categorical_index_array_constructor() { std::cout << "========= array constructor ==========================="; pandas::CategoricalArray arr({"apple", "banana", "apple", "cherry"}); pandas::CategoricalIndex idx(arr, "fruits"); bool passed = (idx.size() == 4 && !idx.empty() && idx.name().has_value() && *idx.name() == "fruits" && idx.inferred_type() == "categorical"); if (!passed) { std::cout << " [FAIL] : in pd_test_categorical_index_array_constructor()" << std::endl; throw std::runtime_error("pd_test_categorical_index_array_constructor failed"); } std::cout << " -> tests passed" << std::endl; } void pd_test_categorical_index_values_constructor() { std::cout << "========= values constructor =========================="; .. _example-intervalindex-item-81: .. dropdown:: item (pd_test_3_all.cpp:3712) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3702 :emphasize-lines: 11 // Test is_interval (always false for base Index) if (int_idx.is_interval()) { throw std::runtime_error("base Index should not be interval"); } std::cout << " -> tests passed" << std::endl; } void pd_test_3_all_index_item() { std::cout << "========= Index.item() ============================="; pandas::Index idx1({42}); numpy::int64 val = idx1.item(); if (val != 42) { throw std::runtime_error("item() should return 42"); } // Test error for size != 1 pandas::Index idx2({1, 2, 3}); .. _example-intervalindex-memory_usage-82: .. dropdown:: memory_usage (pd_test_1_all.cpp:27063) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 27053 :emphasize-lines: 11 } std::cout << "====================================== [OK] pd_test_value_counts test suite ========================== " << std::endl; return 0; } } // namespace dataframe_tests // ------------------- pd_test_value_counts.cpp (end) ----------------------------- // ------------------- pd_test_memory_usage.cpp (start) ----------------------------- // Tests for DataFrame.memory_usage() - pandas-compatible memory usage reporting namespace dataframe_tests { namespace dataframe_tests_memory_usage { void pd_test_memory_usage_basic() { std::cout << "========= basic memory_usage ======================="; // Create a simple DataFrame with multiple columns std::map> data; data["A"] = {1.0, 2.0, 3.0, 4.0, 5.0}; .. _example-intervalindex-mid-83: .. dropdown:: mid (pd_test_1_all.cpp:2124) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2114 :emphasize-lines: 11 // Test right() auto right_arr = arr.right(); if (right_arr.getElementAt({0}) != 2.0 || right_arr.getElementAt({1}) != 5.0 || right_arr.getElementAt({2}) != 10.0) { std::cout << "[FAIL] : in test_left_right_mid_length() : right()" << std::endl; return; } // Test mid() auto mid_arr = arr.mid(); // (0+2)/2=1, (2+5)/2=3.5, (5+10)/2=7.5 auto mid0 = mid_arr[0]; auto mid1 = mid_arr[1]; auto mid2 = mid_arr[2]; if (!mid0.has_value() || std::abs(mid0.value() - 1.0) > 1e-10 || !mid1.has_value() || std::abs(mid1.value() - 3.5) > 1e-10 || !mid2.has_value() || std::abs(mid2.value() - 7.5) > 1e-10) { std::cout << "[FAIL] : in test_left_right_mid_length() : mid()" << std::endl; return; .. _example-intervalindex-overlaps-84: .. dropdown:: overlaps (pd_test_1_all.cpp:2244) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2234 :emphasize-lines: 11 // Test: overlaps method // ============================================================================ void test_overlaps() { std::cout << "========= IntervalArray: overlaps ======================= "; std::vector breaks = {0.0, 2.0, 4.0, 6.0}; // Right-closed: (0, 2], (2, 4], (4, 6] auto arr = pandas::IntervalArrayFloat64::from_breaks(breaks, pandas::IntervalClosed::Right); // Check overlap with (1, 3] auto overlap_1_3 = arr.overlaps(1.0, 3.0); // (0, 2] overlaps (1, 3]? Yes (share 1-2) // (2, 4] overlaps (1, 3]? Yes (share 2-3) // (4, 6] overlaps (1, 3]? No if (overlap_1_3[0].value_or(false) != true || overlap_1_3[1].value_or(false) != true || overlap_1_3[2].value_or(true) != false) { std::cout << "[FAIL] : in test_overlaps() : overlaps (1, 3]" << std::endl; return; } .. _example-intervalindex-overlaps-85: .. dropdown:: overlaps (pd_test_1_all.cpp:2244) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2234 :emphasize-lines: 11 // Test: overlaps method // ============================================================================ void test_overlaps() { std::cout << "========= IntervalArray: overlaps ======================= "; std::vector breaks = {0.0, 2.0, 4.0, 6.0}; // Right-closed: (0, 2], (2, 4], (4, 6] auto arr = pandas::IntervalArrayFloat64::from_breaks(breaks, pandas::IntervalClosed::Right); // Check overlap with (1, 3] auto overlap_1_3 = arr.overlaps(1.0, 3.0); // (0, 2] overlaps (1, 3]? Yes (share 1-2) // (2, 4] overlaps (1, 3]? Yes (share 2-3) // (4, 6] overlaps (1, 3]? No if (overlap_1_3[0].value_or(false) != true || overlap_1_3[1].value_or(false) != true || overlap_1_3[2].value_or(true) != false) { std::cout << "[FAIL] : in test_overlaps() : overlaps (1, 3]" << std::endl; return; } .. _example-intervalindex-putmask-86: .. dropdown:: putmask (pd_test_3_all.cpp:3752) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3742 :emphasize-lines: 11 // Should be at least sizeof index + 5 * sizeof(int64) if (usage < 5 * sizeof(numpy::int64)) { throw std::runtime_error("memory_usage too small"); } std::cout << " -> tests passed" << std::endl; } void pd_test_3_all_index_putmask() { std::cout << "========= Index.putmask() =========================="; pandas::Index idx({1, 2, 3, 4, 5}); numpy::NDArray mask(std::vector{5}); mask.setElementAt({0}, numpy::bool_(true)); mask.setElementAt({1}, numpy::bool_(false)); mask.setElementAt({2}, numpy::bool_(true)); mask.setElementAt({3}, numpy::bool_(false)); mask.setElementAt({4}, numpy::bool_(true)); auto result = idx.putmask(mask, numpy::int64(99)); .. _example-intervalindex-ravel-87: .. dropdown:: ravel (pd_test_3_all.cpp:2147) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2137 :emphasize-lines: 11 throw std::runtime_error("memory_usage shallow too small"); } if (deep < shallow) { throw std::runtime_error("memory_usage deep should be >= shallow"); } std::cout << " -> tests passed" << std::endl; } void pd_test_3_all_categorical_ravel_view() { std::cout << "========= CategoricalArray.ravel()/view() ============="; std::vector> values = {"a", "b", "c"}; pandas::CategoricalArray arr(values); auto raveled = arr.ravel(); if (raveled.size() != 3 || !raveled.equals(arr)) { throw std::runtime_error("ravel failed"); } auto viewed = arr.view(); .. _example-intervalindex-repeat-88: .. dropdown:: repeat (pd_test_3_all.cpp:2166) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2156 :emphasize-lines: 11 auto viewed = arr.view(); if (viewed.size() != 3 || !viewed.equals(arr)) { throw std::runtime_error("view failed"); } std::cout << " -> tests passed" << std::endl; } void pd_test_3_all_categorical_repeat() { std::cout << "========= CategoricalArray.repeat() ==================="; std::vector> values = {"a", "b"}; pandas::CategoricalArray arr(values); auto result = arr.repeat(3); if (result.size() != 6 || *result[0] != "a" || *result[2] != "a" || *result[3] != "b" || *result[5] != "b") { throw std::runtime_error("repeat scalar failed"); } .. _example-intervalindex-repr-89: .. dropdown:: repr (pd_test_1_all.cpp:10906) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 10896 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } void pd_test_extension_index_repr() { std::cout << "========= repr ========================="; pandas::CategoricalArray arr({"a", "b", "c"}); // Use ExtensionIndex directly to test base class repr pandas::ExtensionIndex idx(arr, "test"); std::string repr_str = idx.repr(); bool passed = (!repr_str.empty() && repr_str.find("ExtensionIndex") != std::string::npos); if (!passed) { std::cout << " [FAIL] : in pd_test_extension_index_repr() : repr check failed" << std::endl; throw std::runtime_error("pd_test_extension_index_repr failed"); } std::cout << " -> tests passed" << std::endl; } .. _example-intervalindex-result-90: .. dropdown:: result (pd_test_1_all.cpp:15406) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 15396 :emphasize-lines: 11 data.setElementAt({0}, numpy::datetime64(100LL, numpy::DateTimeUnit::Nanosecond)); data.setElementAt({1}, numpy::datetime64(200LL, numpy::DateTimeUnit::Nanosecond)); numpy::NDArray mask(std::vector{2}); mask.setElementAt({0}, numpy::bool_(false)); mask.setElementAt({1}, numpy::bool_(false)); pandas::DatetimeArray arr(data, mask); pandas::DatetimeIndexBase idx(arr, "original"); // Create join result (int64 values) numpy::NDArray join_result(std::vector{3}); join_result.setElementAt({0}, numpy::int64(500LL)); join_result.setElementAt({1}, numpy::int64(600LL)); join_result.setElementAt({2}, numpy::int64(700LL)); auto new_idx = idx._from_join_target(join_result); bool passed = (new_idx.size() == 3 && new_idx.name().has_value() && *new_idx.name() == "original"); if (!passed) { .. _example-intervalindex-right-91: .. dropdown:: right (pd_test_1_all.cpp:1910) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1900 :emphasize-lines: 11 std::cout << "[FAIL] : in test_constructors() : default constructor size" << std::endl; return; } if (empty.closed() != pandas::IntervalClosed::Right) { std::cout << "[FAIL] : in test_constructors() : default closure" << std::endl; return; } // Constructor from left/right arrays numpy::NDArray left(std::vector{3}); numpy::NDArray right(std::vector{3}); left.setElementAt({0}, 0.0); right.setElementAt({0}, 1.0); left.setElementAt({1}, 1.0); right.setElementAt({1}, 2.0); left.setElementAt({2}, 2.0); right.setElementAt({2}, 3.0); pandas::IntervalArrayFloat64 arr1(left, right); if (arr1.size() != 3) { std::cout << "[FAIL] : in test_constructors() : array size" << std::endl; return; } .. _example-intervalindex-round-92: .. dropdown:: round (pd_test_1_all.cpp:1688) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1678 :emphasize-lines: 11 void pd_test_floating_array_rounding() { std::cout << "========= FloatingArray: rounding ======================= "; pandas::FloatingArray arr({ std::optional(1.234), std::optional(2.567), std::nullopt }); auto rounded = arr.round(2); if (std::abs(rounded[0].value() - 1.23) > 0.001 || std::abs(rounded[1].value() - 2.57) > 0.001) { std::cout << " [FAIL] : in pd_test_floating_array_rounding() : round(2)" << std::endl; throw std::runtime_error("pd_test_floating_array_rounding failed: round(2)"); } if (!rounded.is_na(2)) { std::cout << " [FAIL] : in pd_test_floating_array_rounding() : round should preserve NA" << std::endl; throw std::runtime_error("pd_test_floating_array_rounding failed: NA preservation"); } .. _example-intervalindex-set_closed-93: .. dropdown:: set_closed (pd_test_1_all.cpp:2285) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2275 :emphasize-lines: 11 std::vector breaks = {0.0, 1.0, 2.0}; auto arr = pandas::IntervalArrayFloat64::from_breaks(breaks, pandas::IntervalClosed::Right); if (arr.closed() != pandas::IntervalClosed::Right) { std::cout << "[FAIL] : in test_set_closed() : initial closure" << std::endl; return; } // Change to left-closed auto arr_left = arr.set_closed(pandas::IntervalClosed::Left); if (arr_left.closed() != pandas::IntervalClosed::Left) { std::cout << "[FAIL] : in test_set_closed() : set to Left" << std::endl; return; } // Original should be unchanged if (arr.closed() != pandas::IntervalClosed::Right) { std::cout << "[FAIL] : in test_set_closed() : original changed" << std::endl; return; } .. _example-intervalindex-set_closed-94: .. dropdown:: set_closed (pd_test_1_all.cpp:2285) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2275 :emphasize-lines: 11 std::vector breaks = {0.0, 1.0, 2.0}; auto arr = pandas::IntervalArrayFloat64::from_breaks(breaks, pandas::IntervalClosed::Right); if (arr.closed() != pandas::IntervalClosed::Right) { std::cout << "[FAIL] : in test_set_closed() : initial closure" << std::endl; return; } // Change to left-closed auto arr_left = arr.set_closed(pandas::IntervalClosed::Left); if (arr_left.closed() != pandas::IntervalClosed::Left) { std::cout << "[FAIL] : in test_set_closed() : set to Left" << std::endl; return; } // Original should be unchanged if (arr.closed() != pandas::IntervalClosed::Right) { std::cout << "[FAIL] : in test_set_closed() : original changed" << std::endl; return; } .. _example-intervalindex-set_subtype_override-95: .. dropdown:: set_subtype_override (pd_test_3_all.cpp:24977) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 24967 :emphasize-lines: 11 std::cout << "========= Interval repr float bounds ===================="; pandas::Interval iv(0.0, 1.5); if (iv.repr() != "Interval(0.0, 1.5, closed='right')") throw std::runtime_error("repr mismatch: " + iv.repr()); std::cout << " -> tests passed" << std::endl; } void pd_test_interval_repr_timedelta() { std::cout << "========= Interval repr timedelta subtype ==============="; pandas::Interval iv(0.0, 86400000000000.0); // 1 day in nanos iv.set_subtype_override("timedelta64[ns]"); std::string r = iv.repr(); if (r.find("Timedelta") == std::string::npos) throw std::runtime_error("expected Timedelta in repr: " + r); if (r.find("1 days") == std::string::npos) throw std::runtime_error("expected '1 days' in repr: " + r); std::cout << " -> tests passed" << std::endl; } void pd_test_interval_str_integer() { std::cout << "========= Interval to_string integer bounds ============="; .. _example-intervalindex-slice_indexer-96: .. dropdown:: slice_indexer (pd_test_3_all.cpp:711) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 701 :emphasize-lines: 11 } std::cout << " -> tests passed" << std::endl; } // ============================================================================ // Category 6: Index Indexer Methods // ============================================================================ void pd_test_3_all_index_indexers() { std::cout << "========= Index.get_indexer_for/non_unique/slice_indexer() "; std::vector vals = {"a", "b", "c", "d", "e"}; pandas::Index idx(vals); // Test get_indexer_for() std::vector target = {"b", "d", "f"}; // "f" doesn't exist numpy::NDArray indexer = idx.get_indexer_for(target); if (indexer.getSize() != 3) { std::cout << " [FAIL] : in pd_test_3_all_index_indexers() : get_indexer_for size mismatch" << std::endl; throw std::runtime_error("pd_test_3_all_index_indexers failed: get_indexer_for size"); .. _example-intervalindex-slice_locs-97: .. dropdown:: slice_locs (pd_test_1_all.cpp:18275) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 18265 :emphasize-lines: 11 } std::cout << "-> tests passed" << std::endl; } void pd_test_range_index_slice_locs() { std::cout << "========= slice_locs ================================== "; pandas::RangeIndex ri(0, 10); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] auto [start_idx, stop_idx] = ri.slice_locs(3, 7); bool passed = (start_idx == 3 && stop_idx == 8); if (!passed) { std::cout << " [FAIL] : slice_locs" << std::endl; throw std::runtime_error("pd_test_range_index_slice_locs failed"); } std::cout << "-> tests passed" << std::endl; } .. _example-intervalindex-sort-98: .. dropdown:: sort (pd_test_3_all.cpp:3869) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3859 :emphasize-lines: 11 throw std::runtime_error("last 2 positions should be NaN"); } if (std::abs(result[0] - 3.0) > 0.001) { throw std::runtime_error("shift(-2) [0] should be 3.0"); } std::cout << " -> tests passed" << std::endl; } void pd_test_3_all_index_sort() { std::cout << "========= Index.sort() ============================="; pandas::Index idx({3, 1, 4, 1, 5, 9, 2, 6}); auto result = idx.sort(); if (result[0] != 1 || result[1] != 1 || result[7] != 9) { throw std::runtime_error("sort() not working correctly"); } // Test descending result = idx.sort(false); .. _example-intervalindex-sortlevel-99: .. dropdown:: sortlevel (pd_test_1_all.cpp:14676) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 14666 :emphasize-lines: 11 void pd_test_multiindex_sortlevel() { std::cout << "========= sortlevel =================================== "; std::vector> arrays = { {"b", "a", "c"}, {"2", "1", "3"} }; pandas::MultiIndex mi = pandas::MultiIndex::from_arrays(arrays); auto [sorted, indices] = mi.sortlevel(0); bool passed = true; // After sorting by level 0: a, b, c if (sorted[0][0] != "a" || sorted[1][0] != "b" || sorted[2][0] != "c") { std::cout << " [FAIL] : not sorted correctly by level 0" << std::endl; passed = false; } if (!passed) { .. _example-intervalindex-str-100: .. dropdown:: str (pd_test_1_all.cpp:7137) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 7127 :emphasize-lines: 11 // Test basic info() with stringstream std::map> data = { {"A", {1, 2, 3, 4, 5}}, {"B", {10, 20, 30, 40, 50}}, {"C", {100, 200, 300, 400, 500}} }; pandas::DataFrame df(data); std::ostringstream oss; df.info(oss); std::string output = oss.str(); // Verify key components if (output.find("") == std::string::npos) { std::cout << " [FAIL] : info missing class name" << std::endl; throw std::runtime_error("pd_test_dataframe_info failed: missing class name"); } if (output.find("RangeIndex:") == std::string::npos) { std::cout << " [FAIL] : info missing RangeIndex" << std::endl; throw std::runtime_error("pd_test_dataframe_info failed: missing RangeIndex"); } .. _example-intervalindex-type_id-101: .. dropdown:: type_id (pd_test_3_all.cpp:25592) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 25582 :emphasize-lines: 11 // ------------------- pd_test_value_classify (end) ------------------ // ------------------- pd_test_index_type_id (start) ------------------ namespace dataframe_tests_index_type_id { void pd_test_index_type_id_dispatch() { std::cout << "========= IndexTypeId dispatch ======================="; // RangeIndex ::pandas::RangeIndex ri(0, 5); if (ri.type_id() != ::pandas::IndexTypeId::RangeIndex) throw std::runtime_error("RangeIndex type_id failed"); // Index ::pandas::Index si(std::vector{"a", "b", "c"}); if (si.type_id() != ::pandas::IndexTypeId::IndexString) throw std::runtime_error("Index type_id failed"); // Index ::pandas::Index ii(std::vector{1, 2, 3}); if (ii.type_id() != ::pandas::IndexTypeId::IndexInt64)