• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

llnl-asr / dftracer-utils / 45735107228

26 Nov 2026 01:20AM UTC coverage: 77.696% (+0.4%) from 77.313%
45735107228

push

github

rayandrew
fix: convert natively at the edge and read chunked nested columns safely

to_pandas, from_pandas, table files, loc, reindex, where, unnest and the
dask viewer called pyarrow kernels to convert columns, so they failed
without pyarrow and copied text twice. They now use native codes, masks
and buffers, and pyarrow appears only when a user asks for Arrow.
Readers of list offsets and struct children now go through flat pieces
of a column, so a chunked, selected or dictionary nested column no
longer crashes explode, the CLI printer or child access.

164371 of 253360 branches covered (64.88%)

Branch coverage included in aggregate %.

1455 of 1580 new or added lines in 20 files covered. (92.09%)

795 existing lines in 33 files now uncovered.

190713 of 203655 relevant lines covered (93.65%)

4484549.26 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

74.68
/src/dftracer/utils/python/frame/series.cpp
1
// SPDX-License-Identifier: MIT
2
// A native vec column exposed to Python: the DSL and pipeline operate on our
3
// own SIMD columnar format (dataframe::Series, Highway kernels) and only cross
4
// to Arrow at the edges - construction from a pyarrow array and export via the
5
// Arrow PyCapsule interface (__arrow_c_array__).
6
//
7
// This is the entry translation unit: it owns the SeriesType type object, the
8
// PyMethodDef table, init_series, and the shared make_series
9
// file-static. The method bodies live in series/{arith,math,window,stats,
10
// reduce,string,arrow}.cpp and are declared in series_detail.h.
11

12
#include <dftracer/utils/common/config.h>
13
#include <dftracer/utils/dataframe/c_api.h>
14
#include <dftracer/utils/dataframe/dataframe.h>
15
#include <dftracer/utils/dataframe/internal/column_data.h>
16
#include <dftracer/utils/python/core/api_methods.h>
17
#include <dftracer/utils/python/core/errors.h>
18
#include <dftracer/utils/python/core/method.h>
19
#include <dftracer/utils/python/core/seq_helpers.h>
20
#include <dftracer/utils/python/core/type_helpers.h>
21
#include <dftracer/utils/python/frame/series.h>
22
#include <dftracer/utils/python/frame/series_detail.h>
23

24
#include <cstdint>
25
#include <new>
26
#include <utility>
27

28
namespace dftracer::utils::python::frame::series_detail {
29

30
namespace {
31

32
PyTypeObject SeriesType;
33
// The type the factories allocate: SeriesType until _bind_types gives the
34
// Python subclass.
35
PyTypeObject* g_series_type = &SeriesType;
36

37
void Series_dealloc(SeriesObject* self) {
1,358,609 ✔
38
    if (self->weaklist)
1,358,609 ✔
39
        PyObject_ClearWeakRefs(reinterpret_cast<PyObject*>(self));
4 ✔
40
    self->col.~Series();
1,358,609 !
41
    Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
1,358,609 ✔
42
}
1,358,609 ✔
43

44
}  // namespace
45

46
Series named_like(Series out, const Series& source) {
184,949 ✔
47
    if (out.valid() && source.valid()) {
184,949 ✔
48
        out.handle()->name = source.handle()->name;
184,863 ✔
49
        out.handle()->labels =
277,497 ✔
50
            out.length() == source.length() ? source.handle()->labels : nullptr;
198,408 !
51
    }
92,229 ✔
52
    return out;
184,949 ✔
53
}
92,272 ✔
54

55
Series named_like(Series out, const Series& a, const Series& b) {
6,606 ✔
56
    if (!out.valid()) return out;
6,606 !
57
    out.handle()->name =
6,606 ✔
58
        a.name() == b.name() ? a.handle()->name : dstd::SharedString{};
6,606 ✔
59
    const dftu_series* from = a.has_index() ? a.handle() : b.handle();
6,606 ✔
60
    out.handle()->labels =
9,909 ✔
61
        out.length() == from->length ? from->labels : nullptr;
7,473 !
62
    return out;
6,606 ✔
63
}
3,303 ✔
64

65
PyObject* make_series(Series&& col) {
1,358,683 ✔
66
    if (!col.valid()) {
1,358,683 ✔
67
        PyErr_SetString(core::g_dft_value_error,
70 ✔
68
                        "dataframe kernel produced a null column");
69
        return nullptr;
70 ✔
70
    }
71
    auto* self = reinterpret_cast<SeriesObject*>(
2,037,924 ✔
72
        g_series_type->tp_alloc(g_series_type, 0));
1,358,613 ✔
73
    if (!self) return nullptr;
1,358,613 !
74
    new (&self->col) Series(std::move(col));
1,358,613 ✔
75
    return reinterpret_cast<PyObject*>(self);
1,358,613 ✔
76
}
679,346 ✔
77

78
namespace {
79

80
Py_ssize_t Series_length_sq(PyObject* self) {
88,951 ✔
81
    Series* a = as_native<Series>(self);
88,951 ✔
82
    if (!a) return -1;
88,951 !
83
    return static_cast<Py_ssize_t>(a->length());
88,951 ✔
84
}
44,547 ✔
85

86
// Expose a FLAT, non-null, fixed-width numeric column as a 1-D read-only buffer
87
// so numpy reads it (np.asarray) with no pyarrow. Bit-packed Bool, strings,
88
// nulls, and non-FLAT encodings raise BufferError; the Python wrapper then
89
// falls back to the Arrow path.
90
// The buffer-protocol format and item size of a fixed-width numeric type;
91
// false, with a BufferError set, for any other type.
92
bool numeric_format(TypeId type, const char** fmt, Py_ssize_t* itemsize) {
301,362 ✔
93
    // numpy gives its fixed-width int64 types the C long code where long is 64
94
    // bits. With "q" and "Q" it makes longlong and ulonglong, which pandas
95
    // cannot factorize, so a merge on such a key fails.
96
    constexpr const char* INT64_FORMAT = sizeof(long) == 8 ? "l" : "q";
301,362 ✔
97
    constexpr const char* UINT64_FORMAT = sizeof(long) == 8 ? "L" : "Q";
301,362 ✔
98
    switch (type) {
301,362 ✔
99
        case TypeId::Int8:
21 ✔
100
            *fmt = "b";
42 ✔
101
            *itemsize = 1;
42 ✔
102
            return true;
42 ✔
103
        case TypeId::Int16:
15 ✔
104
            *fmt = "h";
30 ✔
105
            *itemsize = 2;
30 ✔
106
            return true;
30 ✔
107
        case TypeId::Int32:
126 ✔
108
            *fmt = "i";
252 ✔
109
            *itemsize = 4;
252 ✔
110
            return true;
252 ✔
111
        case TypeId::Int64:
78,311 ✔
112
            *fmt = INT64_FORMAT;
156,622 ✔
113
            *itemsize = 8;
156,622 ✔
114
            return true;
156,622 ✔
115
        case TypeId::Uint8:
20 ✔
116
            *fmt = "B";
40 ✔
117
            *itemsize = 1;
40 ✔
118
            return true;
40 ✔
119
        case TypeId::Uint16:
14 ✔
120
            *fmt = "H";
28 ✔
121
            *itemsize = 2;
28 ✔
122
            return true;
28 ✔
123
        case TypeId::Uint32:
14 ✔
124
            *fmt = "I";
28 ✔
125
            *itemsize = 4;
28 ✔
126
            return true;
28 ✔
127
        case TypeId::Uint64:
110 ✔
128
            *fmt = UINT64_FORMAT;
220 ✔
129
            *itemsize = 8;
220 ✔
130
            return true;
220 ✔
131
        case TypeId::Float32:
31 ✔
132
            *fmt = "f";
62 ✔
133
            *itemsize = 4;
62 ✔
134
            return true;
62 ✔
135
        case TypeId::Float64:
8,367 ✔
136
            *fmt = "d";
16,734 ✔
137
            *itemsize = 8;
16,734 ✔
138
            return true;
16,734 ✔
139
        default:
63,652 ✔
140
            PyErr_SetString(PyExc_BufferError,
127,304 ✔
141
                            "Series type has no plain numeric buffer");
142
            return false;
127,304 ✔
143
    }
144
}
150,681 ✔
145

146
int Series_getbuffer(PyObject* self, Py_buffer* view, int flags) {
310,750 ✔
147
    view->obj = nullptr;
310,750 ✔
148
    Series* a = as_native<Series>(self);
310,750 ✔
149
    if (!a) return -1;
310,750 !
150
    if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) {
310,750 !
NEW
151
        PyErr_SetString(PyExc_BufferError, "Series buffer is read-only");
×
NEW
152
        return -1;
×
153
    }
154
    dftu_series* h = a->handle();
310,750 ✔
155
    if (dftu_series_encoding(h) != 0 || dftu_series_null_count(h) != 0) {
310,750 ✔
156
        PyErr_SetString(PyExc_BufferError,
13,978 ✔
157
                        "Series is not a flat, non-null column");
158
        return -1;
13,978 ✔
159
    }
160
    const char* fmt = nullptr;
296,772 ✔
161
    Py_ssize_t itemsize = 0;
296,772 ✔
162
    if (!numeric_format(static_cast<TypeId>(dftu_series_type(h)), &fmt,
296,772 ✔
163
                        &itemsize))
164
        return -1;
63,650 ✔
165
    const void* data = dftu_series_data(h);
169,472 ✔
166
    std::int64_t n = dftu_series_length(h);
169,472 ✔
167
    if (!data && n > 0) {
169,472 !
168
        PyErr_SetString(PyExc_BufferError, "Series has no contiguous buffer");
×
169
        return -1;
×
170
    }
171
    // The values buffer is exposed as-is (zero-copy); shape/stride live in the
172
    // object (constant for an immutable column), so there is nothing to free.
173
    auto* obj = reinterpret_cast<SeriesObject*>(self);
169,472 ✔
174
    obj->buf_shape = static_cast<Py_ssize_t>(n);
169,472 ✔
175
    obj->buf_stride = itemsize;
169,472 ✔
176
    Py_INCREF(self);
169,472 !
177
    view->obj = self;
169,472 ✔
178
    view->buf = const_cast<void*>(data);
169,472 ✔
179
    view->len = static_cast<Py_ssize_t>(n) * itemsize;
169,472 ✔
180
    view->readonly = 1;
169,472 ✔
181
    view->itemsize = itemsize;
169,472 ✔
182
    view->format = (flags & PyBUF_FORMAT) ? const_cast<char*>(fmt) : nullptr;
169,472 !
183
    view->ndim = 1;
169,472 ✔
184
    view->shape = &obj->buf_shape;
169,472 ✔
185
    view->strides = &obj->buf_stride;
169,472 ✔
186
    view->suboffsets = nullptr;
169,472 ✔
187
    view->internal = nullptr;
169,472 ✔
188
    ++obj->exports;
169,472 ✔
189
    return 0;
169,472 ✔
190
}
155,375 ✔
191

192
void Series_releasebuffer(PyObject* self, Py_buffer*) {
169,472 ✔
193
    --reinterpret_cast<SeriesObject*>(self)->exports;
169,472 ✔
194
}
169,472 ✔
195

196
// The values of a FLAT fixed-width numeric column as a buffer, nulls or not
197
// (the values under a null are unspecified). It holds its own share of the
198
// column, so a later _replace of the Series cannot change or free what a view
199
// reads; _values_buffer() wraps it in a memoryview.
200
struct ValuesObject {
201
    PyObject_HEAD Series* col;
202
    const char* format;
203
    Py_ssize_t itemsize;
204
    Py_ssize_t shape;
205
    Py_ssize_t stride;
206
};
207

208
PyTypeObject ValuesType;
209
PyBufferProcs Values_as_buffer = {};
210

211
void Values_dealloc(ValuesObject* self) {
4,586 ✔
212
    // made by dstd::make_unique, so freed by its deleter
213
    dftracer::utils::dstd::UniquePtr<Series>{self->col};
4,586 ✔
214
    Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
4,586 ✔
215
}
4,586 ✔
216

217
int Values_getbuffer(PyObject* self, Py_buffer* view, int flags) {
4,590 ✔
218
    view->obj = nullptr;
4,590 ✔
219
    auto* v = reinterpret_cast<ValuesObject*>(self);
4,590 ✔
220
    if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) {
4,590 !
NEW
221
        PyErr_SetString(PyExc_BufferError, "Series buffer is read-only");
×
NEW
222
        return -1;
×
223
    }
224
    static const char EMPTY = 0;
2,295 ✔
225
    const void* data = dftu_series_data(v->col->handle());
4,590 ✔
226
    if (!data) data = &EMPTY;
4,590 ✔
227
    Py_INCREF(self);
4,590 !
228
    view->obj = self;
4,590 ✔
229
    view->buf = const_cast<void*>(data);
4,590 ✔
230
    view->len = v->shape * v->itemsize;
4,590 ✔
231
    view->readonly = 1;
4,590 ✔
232
    view->itemsize = v->itemsize;
4,590 ✔
233
    view->format =
6,885 ✔
234
        (flags & PyBUF_FORMAT) ? const_cast<char*>(v->format) : nullptr;
4,590 !
235
    view->ndim = 1;
4,590 ✔
236
    view->shape = &v->shape;
4,590 ✔
237
    view->strides = &v->stride;
4,590 ✔
238
    view->suboffsets = nullptr;
4,590 ✔
239
    view->internal = nullptr;
4,590 ✔
240
    return 0;
4,590 ✔
241
}
2,295 ✔
242

243
// _values_buffer() -> a read-only memoryview over the values of a FLAT numeric
244
// column, with no copy and nulls allowed. BufferError for any other column.
245
PyObject* Series_values_buffer(PyObject* self, PyObject*) {
4,592 ✔
246
    Series* a = as_native<Series>(self);
4,592 ✔
247
    if (!a) return nullptr;
4,592 !
248
    dftu_series* h = a->handle();
4,592 ✔
249
    if (dftu_series_encoding(h) != 0) {
4,592 ✔
250
        PyErr_SetString(PyExc_BufferError, "Series is not a flat column");
2 ✔
251
        return nullptr;
2 ✔
252
    }
253
    const char* fmt = nullptr;
4,590 ✔
254
    Py_ssize_t itemsize = 0;
4,590 ✔
255
    if (!numeric_format(static_cast<TypeId>(dftu_series_type(h)), &fmt,
4,590 ✔
256
                        &itemsize))
257
        return nullptr;
2 ✔
258
    const std::int64_t n = dftu_series_length(h);
4,586 ✔
259
    if (!dftu_series_data(h) && n > 0) {
4,586 !
NEW
260
        PyErr_SetString(PyExc_BufferError, "Series has no contiguous buffer");
×
NEW
261
        return nullptr;
×
262
    }
263
    auto* v = PyObject_New(ValuesObject, &ValuesType);
4,586 ✔
264
    if (!v) return nullptr;
4,586 !
265
    v->col = dftracer::utils::dstd::make_unique<Series>(a->share()).release();
4,586 !
266
    v->format = fmt;
4,586 ✔
267
    v->itemsize = itemsize;
4,586 ✔
268
    v->shape = static_cast<Py_ssize_t>(n);
4,586 ✔
269
    v->stride = itemsize;
4,586 ✔
270
    PyObject* view = PyMemoryView_FromObject(reinterpret_cast<PyObject*>(v));
4,586 ✔
271
    Py_DECREF(v);
6,882 !
272
    return view;
2,293 ✔
273
}
2,296 ✔
274

275
// _replace(other): this Series takes the column, the name and the labels of
276
// `other`, in place (setting with enlargement). A numpy array or memoryview
277
// over the old buffers would dangle, so it is a BufferError while one is live.
278
// A kernel that runs with the GIL released reads the column through `Held`, a
279
// share taken under the GIL, so this swap cannot free what it reads.
280
PyObject* Series_replace(PyObject* self, PyObject* other) {
214 ✔
281
    auto* a = reinterpret_cast<SeriesObject*>(self);
214 ✔
282
    Series* o = as_native<Series>(other);
214 ✔
283
    if (!as_native<Series>(self) || !o) return nullptr;
214 !
284
    if (a == reinterpret_cast<SeriesObject*>(other)) Py_RETURN_NONE;
214 !
285
    if (a->exports > 0) {
214 ✔
286
        PyErr_SetString(PyExc_BufferError,
2 ✔
287
                        "cannot replace a Series whose buffer is exported "
288
                        "(a numpy array or memoryview over it is alive)");
289
        return nullptr;
2 ✔
290
    }
291
    return guard([&]() -> PyObject* {
318 ✔
292
        a->col = o->share();
212 !
293
        Py_RETURN_NONE;
212 ✔
294
    });
295
}
107 ✔
296

297
// ---- getters -------------------------------------------------------------
298

299
PyObject* Series_get_type(PyObject* self, void*) {
903,637 ✔
300
    Series* a = as_native<Series>(self);
903,637 ✔
301
    if (!a) return nullptr;
903,637 !
302
    return PyLong_FromLong(static_cast<long>(a->type()));
903,637 ✔
303
}
451,959 ✔
304
PyObject* Series_get_length(PyObject* self, void*) {
1,946 ✔
305
    Series* a = as_native<Series>(self);
1,946 ✔
306
    if (!a) return nullptr;
1,946 !
307
    return PyLong_FromLongLong(a->length());
1,946 ✔
308
}
973 ✔
309
PyObject* Series_get_null_count(PyObject* self, void*) {
494,398 ✔
310
    Series* a = as_native<Series>(self);
494,398 ✔
311
    if (!a) return nullptr;
494,398 !
312
    return PyLong_FromLongLong(a->null_count());
494,398 ✔
313
}
247,199 ✔
314
PyObject* Series_get_encoding(PyObject* self, void*) {
348,572 ✔
315
    Series* a = as_native<Series>(self);
348,572 ✔
316
    if (!a) return nullptr;
348,572 !
317
    return PyLong_FromLong(static_cast<long>(a->encoding()));
348,572 ✔
318
}
174,286 ✔
319
PyObject* Series_get_time_unit(PyObject* self, void*) {
362,862 ✔
320
    Series* a = as_native<Series>(self);
362,862 ✔
321
    if (!a) return nullptr;
362,862 !
322
    return PyLong_FromLong(
362,862 ✔
323
        static_cast<long>(dftu_series_time_unit(a->handle())));
544,293 ✔
324
}
181,431 ✔
325

326
PyObject* Series_get_timezone(PyObject* self, void*) {
353,528 ✔
327
    Series* a = as_native<Series>(self);
353,528 ✔
328
    if (!a) return nullptr;
353,528 !
329
    return PyUnicode_FromString(dftu_series_timezone(a->handle()));
353,528 ✔
330
}
176,764 ✔
331

332
PyObject* Series_get_decimal(PyObject* self, void*) {
3,144 ✔
333
    Series* a = as_native<Series>(self);
3,144 ✔
334
    if (!a) return nullptr;
3,144 !
335
    return Py_BuildValue("(ii)", dftu_series_decimal_precision(a->handle()),
4,716 ✔
336
                         dftu_series_decimal_scale(a->handle()));
4,716 ✔
337
}
1,572 ✔
338

339
PyObject* Series_get_fixed_size(PyObject* self, void*) {
6 ✔
340
    Series* a = as_native<Series>(self);
6 ✔
341
    if (!a) return nullptr;
6 !
342
    return PyLong_FromLong(dftu_series_fixed_size(a->handle()));
6 ✔
343
}
3 ✔
344

345
PyObject* Series_get_is_json(PyObject* self, void*) {
49,856 ✔
346
    Series* a = as_native<Series>(self);
49,856 ✔
347
    if (!a) return nullptr;
49,856 !
348
    return PyBool_FromLong(dftu_series_is_json(a->handle()));
49,856 ✔
349
}
24,928 ✔
350

351
PyObject* Series_get_name(PyObject* self, void*) {
139,871 ✔
352
    Series* a = as_native<Series>(self);
139,871 ✔
353
    if (!a) return nullptr;
139,871 !
354
    const dstd::StringView name = a->name();
139,871 ✔
355
    if (name.empty()) Py_RETURN_NONE;
139,871 ✔
356
    return PyUnicode_FromStringAndSize(name.data(),
122,556 ✔
357
                                       static_cast<Py_ssize_t>(name.size()));
81,839 ✔
358
}
69,733 ✔
359

360
// A name argument as text: an empty view for None. False with a TypeError
361
// naming `what` for anything but a str or None.
362
bool name_from_py(PyObject* arg, const char* what, dstd::StringView& out) {
6,061,165 ✔
363
    if (arg == Py_None) {
6,061,165 ✔
364
        out = dstd::StringView{};
3,124 ✔
365
        return true;
3,124 ✔
366
    }
367
    if (!PyUnicode_Check(arg)) {
6,058,041 ✔
368
        PyErr_Format(PyExc_TypeError, "%s must be a str or None, not %.100s",
15 ✔
369
                     what, Py_TYPE(arg)->tp_name);
10 ✔
370
        return false;
10 ✔
371
    }
372
    Py_ssize_t n = 0;
6,058,031 ✔
373
    const char* p = PyUnicode_AsUTF8AndSize(arg, &n);
6,058,031 ✔
374
    if (!p) return false;
6,058,031 !
375
    out = dstd::StringView(p, static_cast<std::size_t>(n));
6,058,031 ✔
376
    return true;
6,058,031 ✔
377
}
3,030,585 ✔
378

379
PyObject* Series_rename(PyObject* self, PyObject* arg) {
5,246 ✔
380
    Series* a = as_native<Series>(self);
5,246 ✔
381
    if (!a) return nullptr;
5,246 !
382
    dstd::StringView name;
5,246 ✔
383
    if (!name_from_py(arg, "rename: the name", name)) return nullptr;
5,246 ✔
384
    return make_series(a->rename(name));
5,242 !
385
}
2,623 ✔
386

387
// index_names() -> list[str]: the row label levels, in order; [] for none.
388
PyObject* Series_index_names(PyObject* self, PyObject*) {
218,921 ✔
389
    Series* a = as_native<Series>(self);
218,921 ✔
390
    if (!a) return nullptr;
218,921 !
391
    const std::int32_t n = a->index_count();
218,921 ✔
392
    PyObject* list = PyList_New(n);
218,921 ✔
393
    if (!list) return nullptr;
218,921 !
394
    for (std::int32_t i = 0; i < n; ++i) {
270,369 !
395
        const dstd::StringView name = a->index_name(i);
51,448 ✔
396
        PyObject* text = PyUnicode_FromStringAndSize(
77,241 ✔
397
            name.data(), static_cast<Py_ssize_t>(name.size()));
51,448 ✔
398
        if (!text) {
51,448 ✔
399
            Py_DECREF(list);
×
400
            return nullptr;
×
401
        }
402
        PyList_SET_ITEM(list, i, text);
51,448 ✔
403
    }
25,793 !
404
    return list;
109,532 ✔
405
}
109,532 ✔
406

407
// _index_level(i) -> Series: the label column of level i, sharing its buffers.
408
PyObject* Series_index_level(PyObject* self, PyObject* arg) {
16,724 ✔
409
    Series* a = as_native<Series>(self);
16,724 ✔
410
    if (!a) return nullptr;
16,724 !
411
    const long i = PyLong_AsLong(arg);
16,724 ✔
412
    if (i == -1 && PyErr_Occurred()) return nullptr;
16,724 !
413
    if (i < 0 || i >= a->index_count()) {
25,017 !
414
        PyErr_SetString(PyExc_IndexError, "index level out of range");
×
415
        return nullptr;
×
416
    }
417
    return make_series(a->index_level(static_cast<std::int32_t>(i)));
16,724 !
418
}
8,431 ✔
419

420
// _with_index(names, levels) -> Series: a copy sharing the buffers whose row
421
// labels are the `levels` (Series as long as this one) under `names`; empty
422
// lists drop them.
423
PyObject* Series_with_index(PyObject* self, PyObject* args) {
11,631 ✔
424
    Series* a = as_native<Series>(self);
11,631 ✔
425
    if (!a) return nullptr;
11,631 !
426
    PyObject* names_obj = nullptr;
11,631 ✔
427
    PyObject* levels_obj = nullptr;
11,631 ✔
428
    if (!PyArg_ParseTuple(args, "OO", &names_obj, &levels_obj)) return nullptr;
11,631 !
429
    PyObject* names = PySequence_Fast(names_obj, "names must be a sequence");
11,631 ✔
430
    if (!names) return nullptr;
11,631 !
431
    PyObject* levels = PySequence_Fast(levels_obj, "levels must be a sequence");
11,631 ✔
432
    if (!levels) {
11,631 ✔
433
        Py_DECREF(names);
×
434
        return nullptr;
×
435
    }
436
    PyObject* result = nullptr;
11,631 ✔
437
    const Py_ssize_t n = PySequence_Fast_GET_SIZE(names);
11,631 !
438
    if (n != PySequence_Fast_GET_SIZE(levels)) {
11,631 !
439
        PyErr_SetString(PyExc_ValueError,
×
440
                        "with_index: names and levels differ in length");
441
    } else {
442
        dstd::Vector<dstd::StringView> views;
11,631 ✔
443
        dstd::Vector<Series> columns;
11,631 ✔
444
        bool ok = true;
11,631 ✔
445
        for (Py_ssize_t i = 0; ok && i < n; ++i) {
22,066 ✔
446
            dstd::StringView view;
10,435 ✔
447
            const Series* level =
15,655 !
448
                as_native_or_null<Series>(PySequence_Fast_GET_ITEM(levels, i));
10,435 !
449
            if (!level) {
10,435 !
450
                PyErr_SetString(PyExc_TypeError,
×
451
                                "with_index: levels must be Series");
452
                ok = false;
453
            } else if (PySequence_Fast_GET_ITEM(names, i) == Py_None ||
20,870 !
454
                       !name_from_py(PySequence_Fast_GET_ITEM(names, i),
10,435 !
455
                                     "with_index: a level name", view)) {
456
                if (!PyErr_Occurred())
×
457
                    PyErr_SetString(PyExc_TypeError,
×
458
                                    "with_index: a level name must be a str");
459
                ok = false;
460
            } else {
461
                views.push_back(view);
10,435 !
462
                columns.push_back(level->share());
10,435 !
463
            }
464
        }
5,220 ✔
465
        if (ok) {
11,631 ✔
466
            Series out = a->with_index(views, columns);
11,631 !
467
            if (!out.valid())
11,631 !
468
                PyErr_SetString(core::g_dft_value_error,
×
469
                                "with_index: each level must be as long as "
470
                                "the Series, not a list or a struct, and "
471
                                "named apart");
472
            else
473
                result = make_series(std::move(out));
11,631 !
474
        }
11,631 ✔
475
    }
11,631 ✔
476
    Py_DECREF(names);
11,631 !
477
    Py_DECREF(levels);
17,444 !
478
    return result;
5,818 ✔
479
}
5,818 ✔
480

481
// _locate(keys) -> (positions, missing): the rows whose labels equal the key
482
// columns, one per level (see Series::locate).
483
PyObject* Series_locate(PyObject* self, PyObject* keys_obj) {
1,147 ✔
484
    Held held_a(self);
1,147 ✔
485
    Series* a = held_a.get();
1,147 !
486
    if (!a) return nullptr;
1,147 !
487
    dstd::Vector<Series> keys;
1,147 ✔
488
    if (!frame::series_list_from_py(keys_obj, "_locate: keys must be Series",
1,147 !
489
                                    keys))
490
        return nullptr;
491
    return frame::located_to_py(
1,147 !
492
        core::without_gil(a->length(), [&] { return a->locate(keys); }));
2,796 !
493
}
1,649 ✔
494

495
// _locate_range(start, stop) -> (offset, length): the rows between two label
496
// bounds, each a list of one-row Series per level, empty for an open end.
497
PyObject* Series_locate_range(PyObject* self, PyObject* args) {
94 ✔
498
    Held held_a(self);
94 ✔
499
    Series* a = held_a.get();
94 !
500
    if (!a) return nullptr;
94 !
501
    PyObject* start_obj = nullptr;
94 ✔
502
    PyObject* stop_obj = nullptr;
94 ✔
503
    if (!PyArg_ParseTuple(args, "OO", &start_obj, &stop_obj)) return nullptr;
94 !
504
    dstd::Vector<Series> start;
94 ✔
505
    dstd::Vector<Series> stop;
94 ✔
506
    if (!frame::series_list_from_py(
94 !
507
            start_obj, "_locate_range: bounds must be Series", start) ||
188 !
508
        !frame::series_list_from_py(
94 !
509
            stop_obj, "_locate_range: bounds must be Series", stop))
47 ✔
510
        return nullptr;
×
511
    return frame::label_span_to_py(core::without_gil(
141 !
512
        a->length(), [&] { return a->locate_range(start, stop); }));
235 ✔
513
}
141 ✔
514

515
// The options of _reindex: method 0 none, 1 pad, 2 backfill, 3 nearest.
516
bool reindex_options(int method, long long limit, double tolerance,
1,380 ✔
517
                     PyObject* nanos, dataframe::ReindexOptions& out) {
518
    if (method < 0 || method > 3) {
1,380 !
519
        PyErr_SetString(PyExc_ValueError, "_reindex: method must be 0..3");
×
520
        return false;
×
521
    }
522
    out.method = static_cast<dataframe::FillMethod>(method);
1,380 ✔
523
    out.limit = limit;
1,380 ✔
524
    out.tolerance = tolerance;
1,380 ✔
525
    if (nanos != Py_None) {
1,380 ✔
526
        out.tolerance_nanos = PyLong_AsLongLong(nanos);
236 ✔
527
        if (out.tolerance_nanos == -1 && PyErr_Occurred()) return false;
236 !
528
        out.tolerance_is_nanos = true;
236 ✔
529
    }
118 ✔
530
    return true;
690 ✔
531
}
690 ✔
532

533
// _reindex(keys, method, limit, tolerance, fill) -> Series: the column on the
534
// label key Series (one per level) as dataframe::Series::reindex; `fill` is a
535
// one-row Series or None.
536
PyObject* Series_reindex(PyObject* self, PyObject* args) {
1,380 ✔
537
    Held held_a(self);
1,380 ✔
538
    Series* a = held_a.get();
1,380 !
539
    if (!a) return nullptr;
1,380 !
540
    PyObject* keys_obj = nullptr;
1,380 ✔
541
    PyObject* fill_obj = nullptr;
1,380 ✔
542
    PyObject* nanos_obj = Py_None;
1,380 ✔
543
    int method = 0;
1,380 ✔
544
    long long limit = -1;
1,380 ✔
545
    double tolerance = 0;
1,380 ✔
546
    if (!PyArg_ParseTuple(args, "OiLdO|O", &keys_obj, &method, &limit,
1,380 !
547
                          &tolerance, &fill_obj, &nanos_obj))
548
        return nullptr;
549
    dstd::Vector<Series> keys;
1,380 ✔
550
    if (!frame::series_list_from_py(keys_obj, "_reindex: keys must be Series",
1,380 !
551
                                    keys))
552
        return nullptr;
553
    dataframe::ReindexOptions options;
1,380 ✔
554
    if (!reindex_options(method, limit, tolerance, nanos_obj, options))
1,380 !
555
        return nullptr;
556
    Series fill;
1,380 ✔
557
    if (fill_obj != Py_None) {
1,380 ✔
558
        const Series* f = as_native_or_null<Series>(fill_obj);
84 !
559
        if (!f) {
84 !
560
            PyErr_SetString(PyExc_TypeError, "_reindex: fill must be a Series");
×
561
            return nullptr;
562
        }
563
        fill = f->share();
84 !
564
    }
42 !
565
    auto r = core::without_gil(a->length(),
2,070 !
566
                               [&] { return a->reindex(keys, options, fill); });
2,760 !
567
    if (!r) {
1,380 ✔
568
        core::set_py_error(r.error());
134 !
569
        return nullptr;
67 ✔
570
    }
571
    return make_series(std::move(*r));
1,246 !
572
}
2,760 ✔
573

574
// _align(other, how) -> (left, right): the two columns on the joined labels
575
// (see dataframe::align_labels); how is a JoinHow (0 inner, 1 left, 2 right,
576
// 3 outer).
577
PyObject* Series_align(PyObject* self, PyObject* args) {
238 ✔
578
    Held held_a(self, Held::Required, true);
238 ✔
579
    Series* a = held_a.get();
238 !
580
    if (!a) return nullptr;
238 !
581
    PyObject* other_obj = nullptr;
238 ✔
582
    int how = 0;
238 ✔
583
    if (!PyArg_ParseTuple(args, "Oi", &other_obj, &how)) return nullptr;
238 !
584
    Held held_b(other_obj, Held::Required, true);
238 !
585
    Series* b = held_b.get();
238 !
586
    if (!b) return nullptr;
238 !
587
    auto r = core::without_gil(a->length() + b->length(), [&] {
352 !
588
        return dataframe::align_labels(*a, *b,
352 ✔
589
                                       static_cast<dataframe::JoinHow>(how));
238 ✔
590
    });
238 !
591
    if (!r) {
238 ✔
592
        core::set_py_error(r.error());
×
593
        return nullptr;
594
    }
595
    PyObject* left = make_series(std::move(r->left));
238 !
596
    PyObject* right = left ? make_series(std::move(r->right)) : nullptr;
362 !
597
    if (!right) {
238 !
598
        Py_XDECREF(left);
×
599
        return nullptr;
600
    }
601
    return Py_BuildValue("NN", left, right);
238 !
602
}
486 !
603

604
// The name is the one thing a Series changes in place, as pandas and polars
605
// do; the buffers stay shared.
606
int Series_set_name(PyObject* self, PyObject* value, void*) {
6,045,486 ✔
607
    if (!value) {
6,045,486 ✔
608
        PyErr_SetString(PyExc_TypeError, "cannot delete the Series name");
2 ✔
609
        return -1;
2 ✔
610
    }
611
    Series* a = as_native<Series>(self);
6,045,484 ✔
612
    if (!a) return -1;
6,045,484 !
613
    dstd::StringView name;
6,045,484 ✔
614
    if (!name_from_py(value, "a Series name", name)) return -1;
6,045,484 ✔
615
    a->handle()->name =
9,068,217 ✔
616
        name.empty() ? dstd::SharedString{} : dstd::SharedString{name};
9,068,215 ✔
617
    return 0;
6,045,478 ✔
618
}
3,022,743 ✔
619

620
// Series[T] on the native base and every subclass: a generic alias where
621
// Python has one, else the class itself.
622
PyObject* Series_class_getitem(PyObject* cls, [[maybe_unused]] PyObject* args) {
222 ✔
623
#if PY_VERSION_HEX >= 0x03090000
624
    return Py_GenericAlias(cls, args);
222 ✔
625
#else
626
    Py_INCREF(cls);
627
    return cls;
628
#endif
629
}
630

631
PyMethodDef Series_methods[] = {
632
    {"add", DFTU_PYCFUNCTION((core::kw_one<"add", "other", Series_add>)),
633
     METH_VARARGS | METH_KEYWORDS,
634
     "Element-wise addition; mixed dtypes promote to a common type (numpy "
635
     "rules, e.g. uint64 + float64 -> float64)."},
636
    {"sub", DFTU_PYCFUNCTION((core::kw_one<"sub", "other", Series_sub>)),
637
     METH_VARARGS | METH_KEYWORDS,
638
     "Element-wise subtraction; mixed dtypes promote to a common type (numpy "
639
     "rules). Note: uint64 - uint64 wraps on underflow (like numpy); cast to "
640
     "a signed or float dtype first for interval/signed math."},
641
    {"mul", DFTU_PYCFUNCTION((core::kw_one<"mul", "other", Series_mul>)),
642
     METH_VARARGS | METH_KEYWORDS, "Elementwise a * b."},
643
    {"div", Series_div, METH_O, "Elementwise a / b."},
644
    {"add_scalar",
645
     DFTU_PYCFUNCTION((core::kw_one<"add_scalar", "v", Series_add_scalar>)),
646
     METH_VARARGS | METH_KEYWORDS, "Broadcast a + scalar."},
647
    {"sub_scalar",
648
     DFTU_PYCFUNCTION((core::kw_one<"sub_scalar", "v", Series_sub_scalar>)),
649
     METH_VARARGS | METH_KEYWORDS,
650
     "Broadcast a - scalar; a float scalar promotes an integer column to "
651
     "Float64 (numpy's weak-scalar rule). Note: uint64 - v wraps on "
652
     "underflow (like numpy); cast to a signed or float dtype first for "
653
     "interval/signed math."},
654
    {"mul_scalar",
655
     DFTU_PYCFUNCTION((core::kw_one<"mul_scalar", "v", Series_mul_scalar>)),
656
     METH_VARARGS | METH_KEYWORDS, "Broadcast a * scalar."},
657
    {"div_scalar",
658
     DFTU_PYCFUNCTION((core::kw_one<"div_scalar", "v", Series_div_scalar>)),
659
     METH_VARARGS | METH_KEYWORDS, "Broadcast a / scalar."},
660
    {"floordiv",
661
     DFTU_PYCFUNCTION(
662
         (core::kw_pair<"floordiv", Series_floordiv, "other", "reverse">)),
663
     METH_VARARGS | METH_KEYWORDS,
664
     "floordiv(other, reverse=False) -> a // other (a Series or a number; "
665
     "reverse computes other // a), Python's floor rule; a zero divisor is "
666
     "null."},
667
    {"mod",
668
     DFTU_PYCFUNCTION((core::kw_pair<"mod", Series_mod, "other", "reverse">)),
669
     METH_VARARGS | METH_KEYWORDS,
670
     "mod(other, reverse=False) -> a % other with the divisor's sign; a zero "
671
     "divisor is null."},
672
    {"pow",
673
     DFTU_PYCFUNCTION((core::kw_pair<"pow", Series_pow, "other", "reverse">)),
674
     METH_VARARGS | METH_KEYWORDS,
675
     "pow(other, reverse=False) -> a ** other; Int64 for two integers (a "
676
     "negative exponent is null), else Float64."},
677
    {"_cast", Series_cast, METH_O,
678
     "Cast to a TypeId code; TypeError names both types for a pair the engine "
679
     "refuses."},
680
    {"prim", DFTU_PYCFUNCTION((core::kw_one<"prim", "op", Series_prim>)),
681
     METH_VARARGS | METH_KEYWORDS,
682
     "Apply a unary numeric primitive by Prim code (i64 in, i64 out)."},
683
    {"compare", Series_compare, METH_VARARGS,
684
     "compare(op, scalar) -> Bool column (op is a DFTU_CMP_* code)."},
685
    {"logical",
686
     DFTU_PYCFUNCTION(
687
         (core::kw_pair<"logical", Series_logical, "op", "other">)),
688
     METH_VARARGS | METH_KEYWORDS,
689
     "logical(op, other) -> Bool column (op is a DFTU_LOGICAL_* code)."},
690
    {"__arrow_c_stream__", Series_arrow_c_stream, METH_VARARGS,
691
     "Stream the column: one Arrow array per chunk."},
692
    {"__arrow_c_array__", Series_arrow_c_array, METH_VARARGS,
693
     "Arrow PyCapsule export: (schema_capsule, array_capsule)."},
694
    {"quantile", DFTU_PYCFUNCTION(Series_quantile),
695
     METH_VARARGS | METH_KEYWORDS,
696
     "quantile(q=0.5, interpolation='linear') -> float: the exact quantile of "
697
     "the valid values. interpolation is 'linear', 'nearest', 'lower', "
698
     "'higher' or 'midpoint'; a NaN value ranks above every number."},
699
    {"median", Series_median, METH_NOARGS, "Median (quantile 0.5)."},
700
    {"variance", DFTU_PYCFUNCTION(Series_variance),
701
     METH_VARARGS | METH_KEYWORDS, "variance(sample=True) -> float."},
702
    {"stddev", DFTU_PYCFUNCTION(Series_stddev), METH_VARARGS | METH_KEYWORDS,
703
     "stddev(sample=True) -> float."},
704
    {"value_counts", Series_value_counts, METH_NOARGS,
705
     "value_counts() -> DataFrame of distinct values and counts, "
706
     "most-frequent first."},
707
    {"is_sorted", DFTU_PYCFUNCTION(Series_is_sorted),
708
     METH_VARARGS | METH_KEYWORDS, "is_sorted(descending=False) -> bool."},
709
    {"is_in", Series_is_in, METH_O,
710
     "is_in(values) -> Bool mask where the value is in the values Series."},
711
    {"sort", DFTU_PYCFUNCTION(Series_sort), METH_VARARGS | METH_KEYWORDS,
712
     "sort(descending=False, nulls_last=False) -> sorted Series; nulls first "
713
     "unless nulls_last."},
714
    {"head", DFTU_PYCFUNCTION(Series_head), METH_VARARGS | METH_KEYWORDS,
715
     "head(n=5) -> first n rows Series."},
716
    {"tail", DFTU_PYCFUNCTION(Series_tail), METH_VARARGS | METH_KEYWORDS,
717
     "tail(n=5) -> last n rows Series."},
718
    {"shift", Series_shift, METH_O,
719
     "shift(n) -> Series shifted by n (vacated rows null)."},
720
    {"top_k", DFTU_PYCFUNCTION((core::kw_one<"top_k", "k", Series_top_k>)),
721
     METH_VARARGS | METH_KEYWORDS, "top_k(k) -> the k largest rows Series."},
722
    {"bottom_k",
723
     DFTU_PYCFUNCTION((core::kw_one<"bottom_k", "k", Series_bottom_k>)),
724
     METH_VARARGS | METH_KEYWORDS,
725
     "bottom_k(k) -> the k smallest rows Series."},
726
    {"sample", DFTU_PYCFUNCTION(Series_sample), METH_VARARGS | METH_KEYWORDS,
727
     "sample(n, seed=0) -> deterministic sample of n rows Series."},
728
    {"rank", DFTU_PYCFUNCTION(Series_rank), METH_VARARGS | METH_KEYWORDS,
729
     "rank(method='average', descending=False) -> Float64 Series "
730
     "(method: average|min|dense|ordinal)."},
731
    {"rolling", DFTU_PYCFUNCTION(Series_rolling), METH_VARARGS | METH_KEYWORDS,
732
     "rolling(window, op=None) -> the Rolling window of window rows, or with "
733
     "op (sum|mean|min|max) the Float64 Series of that reduction."},
734
    {"rolling_sum",
735
     DFTU_PYCFUNCTION(
736
         (core::kw_one<"rolling_sum", "window", Series_rolling_sum>)),
737
     METH_VARARGS | METH_KEYWORDS,
738
     "rolling_sum(window) -> Float64 Series of per-window sums."},
739
    {"rolling_mean",
740
     DFTU_PYCFUNCTION(
741
         (core::kw_one<"rolling_mean", "window", Series_rolling_mean>)),
742
     METH_VARARGS | METH_KEYWORDS,
743
     "rolling_mean(window) -> Float64 Series of per-window means."},
744
    {"rolling_min",
745
     DFTU_PYCFUNCTION(
746
         (core::kw_one<"rolling_min", "window", Series_rolling_min>)),
747
     METH_VARARGS | METH_KEYWORDS,
748
     "rolling_min(window) -> Float64 Series of per-window minima."},
749
    {"rolling_max",
750
     DFTU_PYCFUNCTION(
751
         (core::kw_one<"rolling_max", "window", Series_rolling_max>)),
752
     METH_VARARGS | METH_KEYWORDS,
753
     "rolling_max(window) -> Float64 Series of per-window maxima."},
754
    {"ewm", DFTU_PYCFUNCTION(Series_ewm), METH_VARARGS | METH_KEYWORDS,
755
     "ewm(alpha=None, *, span=None, com=None, halflife=None) -> the Ewm "
756
     "window; pass exactly one parameter."},
757
    {"rolling_quantile",
758
     DFTU_PYCFUNCTION((core::kw_pair<"rolling_quantile",
759
                                     Series_rolling_quantile, "window", "q">)),
760
     METH_VARARGS | METH_KEYWORDS,
761
     "rolling_quantile(window, q) -> Float64 Series of per-window quantile q."},
762
    {"ewm_mean",
763
     DFTU_PYCFUNCTION((core::kw_one<"ewm_mean", "alpha", Series_ewm_mean>)),
764
     METH_VARARGS | METH_KEYWORDS,
765
     "ewm_mean(alpha) -> Float64 Series, exponentially weighted mean."},
766
    {"ewm_std",
767
     DFTU_PYCFUNCTION((core::kw_one<"ewm_std", "alpha", Series_ewm_std>)),
768
     METH_VARARGS | METH_KEYWORDS,
769
     "ewm_std(alpha) -> Float64 Series, exponentially weighted sample std."},
770
    {"cut", Series_cut, METH_VARARGS,
771
     "cut(breaks, flags=0) -> Int32 Series binning by the ascending breaks "
772
     "Series; flags 1 closes each interval on the right, 2 gives null outside "
773
     "the interior intervals and numbers them from 0."},
774
    {"qcut", DFTU_PYCFUNCTION((core::kw_one<"qcut", "q", Series_qcut>)),
775
     METH_VARARGS | METH_KEYWORDS,
776
     "qcut(q) -> Int32 Series binning by the column's q-quantile edges."},
777
    {"search_sorted", DFTU_PYCFUNCTION(Series_search_sorted),
778
     METH_VARARGS | METH_KEYWORDS,
779
     "search_sorted(element, side='left') -> Int64 Series of the insertion "
780
     "indices; side 'right' inserts after equal values ('any' is 'left')."},
781
    {"unique", DFTU_PYCFUNCTION(Series_unique), METH_VARARGS | METH_KEYWORDS,
782
     "unique(maintain_order=False) -> the distinct values, a null kept once: "
783
     "sorted with the null first, or in order of first occurrence."},
784
    {"duplicated", DFTU_PYCFUNCTION(Series_duplicated),
785
     METH_VARARGS | METH_KEYWORDS,
786
     "duplicated(keep='first') -> Bool mask of the repeats; keep 'first' or "
787
     "'last' leaves that row unmarked, False marks every repeated row."},
788
    {"dot", DFTU_PYCFUNCTION((core::kw_one<"dot", "other", Series_dot>)),
789
     METH_VARARGS | METH_KEYWORDS,
790
     "dot(other) -> scalar sum of x[i]*y[i] over non-null pairs (SIMD)."},
791
    {"sum", series_reduce_scalar<&Series::sum>, METH_NOARGS,
792
     "Sum of the valid values; a bool column counts True as 1, so (x > "
793
     "2).sum() counts the matches. Raises TypeError for a column type with "
794
     "no sum (string, most temporal types)."},
795
    {"min", series_reduce_scalar<&Series::min>, METH_NOARGS,
796
     "Smallest valid value, None when no value is valid. A bool column gives "
797
     "0 or 1 and a string column the bytewise smallest string; raises "
798
     "TypeError for a type with no order here."},
799
    {"max", series_reduce_scalar<&Series::max>, METH_NOARGS,
800
     "Largest valid value, over the same column types as min; None when no "
801
     "value is valid."},
802
    {"mean", series_reduce_f64<&Series::mean>, METH_NOARGS,
803
     "Mean of the valid values, None when no value is valid; a bool column "
804
     "gives the fraction that is True. Raises TypeError for a column type with "
805
     "no sum."},
806
    {"all", Series_all, METH_NOARGS,
807
     "Whether every non-null Bool value is true."},
808
    {"any", Series_any, METH_NOARGS,
809
     "Whether any non-null Bool value is true."},
810
    {"take", Series_take, METH_O,
811
     "take(indices) -> Series gathered at the given row indices."},
812
    {"where", Series_where, METH_VARARGS,
813
     "where(mask, other) -> Series: this value where the Bool mask is true, "
814
     "else other's (a null mask row takes other)."},
815
    {"filter",
816
     DFTU_PYCFUNCTION((core::kw_one<"filter", "predicate", Series_filter>)),
817
     METH_VARARGS | METH_KEYWORDS,
818
     "filter(mask) -> Series keeping rows where the Bool mask is true."},
819
    {"argsort", DFTU_PYCFUNCTION(Series_argsort), METH_VARARGS | METH_KEYWORDS,
820
     "argsort(descending=False, nulls_last=True) -> Int64 Series of the "
821
     "sorted row order; nulls last unless nulls_last is False."},
822
    {"arg_sort", DFTU_PYCFUNCTION(Series_arg_sort),
823
     METH_VARARGS | METH_KEYWORDS,
824
     "arg_sort(descending=False, nulls_last=False) -> Int64 Series of the "
825
     "sorted row order; nulls first unless nulls_last."},
826
    {"dictionary_encode", Series_dictionary_encode, METH_NOARGS,
827
     "Dictionary-encode a String/Binary column -> Series."},
828
    {"_str_into", Series_str_into, METH_VARARGS,
829
     "_str_into(out, na=None): a String column's rows into a numpy object "
830
     "array of its length, null rows holding `na`."},
831
    {"_np_parts", Series_np_parts, METH_VARARGS,
832
     "_np_parts(nullable=False, na=None) -> (values, mask, dtype): the column "
833
     "in one native pass for numpy.frombuffer (bytearrays; a list of str for "
834
     "a String column, null rows holding `na`); mask is 1 = null or None."},
835
    {"_to_pylist", Series_to_pylist, METH_NOARGS,
836
     "_to_pylist() -> list of Python values, None for null; TypeError for a "
837
     "column type with no native conversion."},
838
    {"_dictionary_parts", Series_dictionary_parts, METH_NOARGS,
839
     "_dictionary_parts() -> (codes, values): the FLAT Int32 codes and the "
840
     "values column of a dictionary-encoded column, sharing its buffers."},
841
    {"_values_buffer", Series_values_buffer, METH_NOARGS,
842
     "_values_buffer() -> memoryview: the values of a flat numeric column, "
843
     "nulls included (unspecified under a null), with no copy."},
844
    {"_plain_text", Series_plain_text, METH_NOARGS,
845
     "_plain_text() -> Series: the column with each view string column (at "
846
     "the top, in the dictionary or in a chunk) made flat; the rest shared."},
847
    {"_joined_dictionary", Series_joined_dictionary, METH_NOARGS,
848
     "_joined_dictionary() -> Series or None: a chunked column of dictionary "
849
     "chunks as one dictionary column; None for any other column."},
850
    {"_nulls_like", Series_nulls_like, METH_O,
851
     "_nulls_like(n) -> Series: n null rows of this column's full type."},
852
    {"_null_bytes", Series_null_bytes, METH_NOARGS,
853
     "_null_bytes() -> bytearray or None: a byte per row, 1 where the row is "
854
     "null; None when there are no nulls."},
855
    {"_physical", Series_physical, METH_NOARGS,
856
     "_physical() -> Series: the integers of a date, time, timestamp, "
857
     "duration or float16 column (buffers shared)."},
858
    {"to_bytes", Series_to_bytes, METH_NOARGS,
859
     "to_bytes() -> bytes: the column in the native frame format."},
860
    {"item", Series_item, METH_O,
861
     "item(i) -> the value at row i as a Python object (None for null)."},
862
    {"_item_unlabelled", Series_item_unlabelled, METH_O,
863
     "_item_unlabelled(i) -> the element at position i; NotImplementedError "
864
     "on a Series with row labels."},
865
    {"materialize", Series_materialize, METH_NOARGS,
866
     "Materialize any encoding to a new FLAT Series (gather)."},
867
    {"__class_getitem__", Series_class_getitem, METH_O | METH_CLASS,
868
     "Series[T]: a generic alias, for annotations."},
869
    {"rename", Series_rename, METH_O,
870
     "rename(name) -> a new Series sharing this column's buffers, named name "
871
     "(a str) or unnamed (None). Only the scalar form of pandas' rename is "
872
     "supported."},
873
    {"share", Series_share, METH_NOARGS,
874
     "A new owned Series sharing this column's buffers zero-copy."},
875
    {"index_names", Series_index_names, METH_NOARGS,
876
     "index_names() -> list[str]\n\nThe row label levels, in order; [] for "
877
     "a positional Series."},
878
    {"_index_level", Series_index_level, METH_O,
879
     "_index_level(i) -> Series: the label column of level i."},
880
    {"_locate", Series_locate, METH_O,
881
     "_locate(keys) -> (positions, missing): the rows whose row labels equal "
882
     "the key Series (one per level), and the keys no label matches."},
883
    {"_locate_range", Series_locate_range, METH_VARARGS,
884
     "_locate_range(start, stop) -> (offset, length): the rows between two "
885
     "label bounds (lists of one-row Series, empty for an open end)."},
886
    {"_reindex", Series_reindex, METH_VARARGS,
887
     "_reindex(keys, method, limit, tolerance, fill) -> Series on the label "
888
     "key "
889
     "Series (one per level); method 0 none, 1 pad, 2 backfill, 3 nearest, "
890
     "limit -1 for none, tolerance infinite for none, fill a one-row Series or "
891
     "None, nanos a tolerance as whole nanoseconds for temporal labels."},
892
    {"_align", Series_align, METH_VARARGS,
893
     "_align(other, how) -> (left, right) on the joined labels; how is 0 "
894
     "inner, "
895
     "1 left, 2 right, 3 outer."},
896
    {"_replace", Series_replace, METH_O,
897
     "_replace(other) -> None: this Series takes the column, name and labels "
898
     "of `other` in place; BufferError while a buffer export is live."},
899
    {"_with_index", Series_with_index, METH_VARARGS,
900
     "_with_index(names, levels) -> Series sharing this column's buffers "
901
     "whose row labels are the level Series; empty lists drop them."},
902
    {"slice",
903
     DFTU_PYCFUNCTION(
904
         (core::kw_pair<"slice", Series_slice, "offset", "length">)),
905
     METH_VARARGS | METH_KEYWORDS,
906
     "slice(offset, length) -> view Series of a row range, sharing the "
907
     "value buffers and keeping the layout; raises for list, map and struct."},
908
    {"str_eq", DFTU_PYCFUNCTION((core::kw_one<"str_eq", "rhs", Series_str_eq>)),
909
     METH_VARARGS | METH_KEYWORDS,
910
     "str_eq(rhs) -> Bool Series where the string equals rhs."},
911
    {"str_contains",
912
     DFTU_PYCFUNCTION(
913
         (core::kw_one<"str_contains", "needle", Series_str_contains>)),
914
     METH_VARARGS | METH_KEYWORDS,
915
     "str_contains(needle) -> Bool Series where the string contains needle."},
916
    {"str_starts_with",
917
     DFTU_PYCFUNCTION(
918
         (core::kw_one<"str_starts_with", "prefix", Series_str_starts_with>)),
919
     METH_VARARGS | METH_KEYWORDS,
920
     "str_starts_with(prefix) -> Bool Series where the string starts with "
921
     "prefix."},
922
    {"str_ends_with",
923
     DFTU_PYCFUNCTION(
924
         (core::kw_one<"str_ends_with", "suffix", Series_str_ends_with>)),
925
     METH_VARARGS | METH_KEYWORDS,
926
     "str_ends_with(suffix) -> Bool Series where the string ends with suffix."},
927
    {"str_like",
928
     DFTU_PYCFUNCTION((core::kw_one<"str_like", "pattern", Series_str_like>)),
929
     METH_VARARGS | METH_KEYWORDS,
930
     "str_like(pattern) -> Bool Series matching the SQL LIKE / glob pattern "
931
     "(% any run, _ one char, backslash escapes a literal %/_/backslash)."},
932
    {"str_matches",
933
     DFTU_PYCFUNCTION(
934
         (core::kw_one<"str_matches", "pattern", Series_str_matches>)),
935
     METH_VARARGS | METH_KEYWORDS,
936
     "str_matches(pattern) -> Bool Series where the whole string matches the "
937
     "duql regex."},
938
    {"str_search",
939
     DFTU_PYCFUNCTION(
940
         (core::kw_one<"str_search", "pattern", Series_str_search>)),
941
     METH_VARARGS | METH_KEYWORDS,
942
     "str_search(pattern) -> Bool Series where the duql regex matches "
943
     "anywhere in the string."},
944
    {"str_find",
945
     DFTU_PYCFUNCTION((core::kw_one<"str_find", "needle", Series_str_find>)),
946
     METH_VARARGS | METH_KEYWORDS,
947
     "str_find(needle) -> Int64 Series of the first byte index, or -1."},
948
    {"str_replace",
949
     DFTU_PYCFUNCTION(
950
         (core::kw_pair<"str_replace", Series_str_replace, "pat", "repl">)),
951
     METH_VARARGS | METH_KEYWORDS,
952
     "str_replace(pat, repl) -> String Series, first literal occurrence."},
953
    {"str_replace_all",
954
     DFTU_PYCFUNCTION((core::kw_pair<"str_replace_all", Series_str_replace_all,
955
                                     "pat", "repl">)),
956
     METH_VARARGS | METH_KEYWORDS,
957
     "str_replace_all(pat, repl) -> String Series, all literal occurrences."},
958
    {"str_slice",
959
     DFTU_PYCFUNCTION(
960
         (core::kw_pair<"str_slice", Series_str_slice, "start", "length">)),
961
     METH_VARARGS | METH_KEYWORDS,
962
     "str_slice(start, length=-1) -> String Series substring by byte offset."},
963
    {"str_pad_start", DFTU_PYCFUNCTION(Series_str_pad_start),
964
     METH_VARARGS | METH_KEYWORDS,
965
     "str_pad_start(width, fill=' ') -> left-padded String Series."},
966
    {"str_pad_end", DFTU_PYCFUNCTION(Series_str_pad_end),
967
     METH_VARARGS | METH_KEYWORDS,
968
     "str_pad_end(width, fill=' ') -> right-padded String Series."},
969
    {"str_zfill",
970
     DFTU_PYCFUNCTION((core::kw_one<"str_zfill", "width", Series_str_zfill>)),
971
     METH_VARARGS | METH_KEYWORDS,
972
     "str_zfill(width) -> String Series left-padded with '0' after any sign."},
973
    {"str_split",
974
     DFTU_PYCFUNCTION((core::kw_one<"str_split", "sep", Series_str_split>)),
975
     METH_VARARGS | METH_KEYWORDS,
976
     "str_split(sep) -> List<String> Series split on the literal sep."},
977
    {"str_extract",
978
     DFTU_PYCFUNCTION((
979
         core::kw_pair<"str_extract", Series_str_extract, "pattern", "group">)),
980
     METH_VARARGS | METH_KEYWORDS,
981
     "str_extract(pattern, group=1) -> String Series of the regex capture "
982
     "group per row, null where there is no match."},
983
    {"str_regex_replace",
984
     DFTU_PYCFUNCTION(
985
         (core::kw_pair<"str_regex_replace", Series_str_regex_replace,
986
                        "pattern", "to">)),
987
     METH_VARARGS | METH_KEYWORDS,
988
     "str_regex_replace(pattern, to) -> String Series with every regex match "
989
     "replaced by to ($n, ${n}, ${name} insert a group, $$ a dollar sign). "
990
     "Raises ValueError for an invalid pattern or replacement."},
991
    {"list_get",
992
     DFTU_PYCFUNCTION((core::kw_one<"list_get", "index", Series_list_get>)),
993
     METH_VARARGS | METH_KEYWORDS,
994
     "list_get(index) -> the element at index of each row's list (negative "
995
     "from the end), null where the list is too short."},
996
    {"list_join",
997
     DFTU_PYCFUNCTION((core::kw_one<"list_join", "sep", Series_list_join>)),
998
     METH_VARARGS | METH_KEYWORDS,
999
     "list_join(sep) -> each row's list of strings joined with sep."},
1000
    {"str_case",
1001
     DFTU_PYCFUNCTION((core::kw_one<"str_case", "code", Series_str_case>)),
1002
     METH_VARARGS | METH_KEYWORDS,
1003
     "str_case(code) -> ASCII case form: 0 capitalize, 1 title, 2 swapcase."},
1004
    {"str_is",
1005
     DFTU_PYCFUNCTION((core::kw_one<"str_is", "code", Series_str_is>)),
1006
     METH_VARARGS | METH_KEYWORDS,
1007
     "str_is(code) -> Bool: 0 alnum, 1 alpha, 2 digit, 3 decimal, 4 numeric, "
1008
     "5 space, 6 lower, 7 upper, 8 title (ASCII; an empty string is false)."},
1009
    {"str_count",
1010
     DFTU_PYCFUNCTION((core::kw_one<"str_count", "pat", Series_str_count>)),
1011
     METH_VARARGS | METH_KEYWORDS,
1012
     "str_count(pat) -> Int64 non-overlapping occurrences of the literal."},
1013
    {"str_rfind",
1014
     DFTU_PYCFUNCTION((core::kw_one<"str_rfind", "needle", Series_str_rfind>)),
1015
     METH_VARARGS | METH_KEYWORDS,
1016
     "str_rfind(needle) -> Int64 byte index of the last occurrence, or -1."},
1017
    {"str_remove_prefix",
1018
     DFTU_PYCFUNCTION((core::kw_one<"str_remove_prefix", "prefix",
1019
                                    Series_str_remove_prefix>)),
1020
     METH_VARARGS | METH_KEYWORDS,
1021
     "str_remove_prefix(prefix) -> each row without a leading prefix."},
1022
    {"str_remove_suffix",
1023
     DFTU_PYCFUNCTION((core::kw_one<"str_remove_suffix", "suffix",
1024
                                    Series_str_remove_suffix>)),
1025
     METH_VARARGS | METH_KEYWORDS,
1026
     "str_remove_suffix(suffix) -> each row without a trailing suffix."},
1027
    {"str_repeat",
1028
     DFTU_PYCFUNCTION((core::kw_one<"str_repeat", "n", Series_str_repeat>)),
1029
     METH_VARARGS | METH_KEYWORDS,
1030
     "str_repeat(n) -> each row repeated n times."},
1031
    {"str_center", DFTU_PYCFUNCTION(Series_str_center),
1032
     METH_VARARGS | METH_KEYWORDS,
1033
     "str_center(width, fill=' ') -> each row centered in width bytes."},
1034
    {"str_cat",
1035
     DFTU_PYCFUNCTION((core::kw_one<"str_cat", "other", Series_str_cat>)),
1036
     METH_VARARGS | METH_KEYWORDS,
1037
     "str_cat(other) -> row-wise concatenation with another String Series."},
1038
    {"str_findall",
1039
     DFTU_PYCFUNCTION(
1040
         (core::kw_one<"str_findall", "pattern", Series_str_findall>)),
1041
     METH_VARARGS | METH_KEYWORDS,
1042
     "str_findall(pattern) -> List<String> of every regex match per row."},
1043
    {"str_partition", DFTU_PYCFUNCTION(Series_str_partition),
1044
     METH_VARARGS | METH_KEYWORDS,
1045
     "str_partition(sep, from_right=False) -> List<String> of (head, sep, "
1046
     "tail) per row at the first (last) occurrence."},
1047
    {"str_normalize",
1048
     DFTU_PYCFUNCTION(
1049
         (core::kw_one<"str_normalize", "form", Series_str_normalize>)),
1050
     METH_VARARGS | METH_KEYWORDS,
1051
     "str_normalize(form) -> each row in the Unicode form (0 NFC, 1 NFKC, "
1052
     "2 NFD, 3 NFKD); null for a row that is not valid UTF-8."},
1053
    {"str_translate",
1054
     DFTU_PYCFUNCTION(
1055
         (core::kw_pair<"str_translate", Series_str_translate, "from_", "to">)),
1056
     METH_VARARGS | METH_KEYWORDS,
1057
     "str_translate(from, to) -> each codepoint of every row replaced by the "
1058
     "String Series pair: from holds one codepoint per row, to the "
1059
     "replacement (null deletes)."},
1060
    {"str_wrap",
1061
     DFTU_PYCFUNCTION(
1062
         (core::kw_pair<"str_wrap", Series_str_wrap, "width", "flags">)),
1063
     METH_VARARGS | METH_KEYWORDS,
1064
     "str_wrap(width, flags) -> each row as textwrap.wrap lines joined by a "
1065
     "newline; flags is an OR of 1 expand_tabs, 2 replace_whitespace, "
1066
     "4 drop_whitespace, 8 break_long_words, 16 break_on_hyphens."},
1067
    {"dt_part",
1068
     DFTU_PYCFUNCTION(
1069
         (core::kw_pair<"dt_part", Series_dt_part, "code", "unit">)),
1070
     METH_VARARGS | METH_KEYWORDS,
1071
     "dt_part(code, unit=2) -> Int64 calendar part (0 year .. 16 epoch days) "
1072
     "of a Timestamp / Date / Duration column, or an Int64 column read in "
1073
     "unit (0 s, 1 ms, 2 us, 3 ns)."},
1074
    {"dt_format",
1075
     DFTU_PYCFUNCTION(
1076
         (core::kw_pair<"dt_format", Series_dt_format, "fmt", "unit">)),
1077
     METH_VARARGS | METH_KEYWORDS,
1078
     "dt_format(fmt, unit=2) -> String strftime of a Timestamp / Date column, "
1079
     "or an Int64 column read in unit (0 s, 1 ms, 2 us, 3 ns); a Timestamp "
1080
     "uses its own unit. Directives: %Y %y %m %d %H %I %M %S %f %j %a %A %b "
1081
     "%B %p %F %T %s %z %Z %%. Raises ValueError for another directive."},
1082
    {"dt_round",
1083
     DFTU_PYCFUNCTION(
1084
         (core::kw_pair<"dt_round", Series_dt_round, "every", "mode">)),
1085
     METH_VARARGS | METH_KEYWORDS,
1086
     "dt_round(every, mode) -> each instant rounded to a multiple of every "
1087
     "(the column's unit) by mode 0 floor, 1 ceil, 2 round (half to even)."},
1088
    {"dt_as_unit",
1089
     DFTU_PYCFUNCTION(
1090
         (core::kw_pair<"dt_as_unit", Series_dt_as_unit, "unit", "mode">)),
1091
     METH_VARARGS | METH_KEYWORDS,
1092
     "dt_as_unit(unit, mode=0) -> this Timestamp or Duration column in unit "
1093
     "(0 s, 1 ms, 2 us, 3 ns), the instant kept, a coarser unit floored "
1094
     "(mode 0) or, for a Duration, truncated toward zero as polars (mode 1). "
1095
     "Raises ValueError on overflow."},
1096
    {"with_timezone",
1097
     DFTU_PYCFUNCTION(
1098
         (core::kw_one<"with_timezone", "tz", Series_with_timezone>)),
1099
     METH_VARARGS | METH_KEYWORDS,
1100
     "with_timezone(tz) -> this Timestamp column under zone tz ('' for "
1101
     "naive), the same instants and buffers."},
1102
    {"dt_tz_localize", DFTU_PYCFUNCTION(Series_tz_localize),
1103
     METH_VARARGS | METH_KEYWORDS,
1104
     "dt_tz_localize(tz, ambiguous=0, nonexistent=0, shift=0) -> naive "
1105
     "Timestamp column read as wall times in zone tz, as UTC instants. "
1106
     "ambiguous: 0 raise, 1 earliest, 2 latest, 3 null, 4 infer. nonexistent: "
1107
     "0 raise, 1 shift forward, 2 shift backward, 3 null, 4 shift by `shift` "
1108
     "ticks. A column with a zone and tz '' gives its wall times, naive."},
1109
    {"is_null_at", Series_is_null, METH_O,
1110
     "is_null_at(i) -> whether row i is null."},
1111
    {"num_children", Series_num_children, METH_NOARGS,
1112
     "Child count: 1 for a List, the field count for a Struct, else 0."},
1113
    {"child", DFTU_PYCFUNCTION((core::kw_one<"child", "i", Series_child>)),
1114
     METH_VARARGS | METH_KEYWORDS,
1115
     "child(i) -> child Series (List: 0=values; Struct: field i)."},
1116
#define API_PICK_Series(id, name, args, doc) API_ENTRY(id, name, args, doc)
1117
#define API_PICK_Str(id, name, args, doc)
1118
#define API_PICK_Dt(id, name, args, doc)
1119
#define API_PICK_List(id, name, args, doc)
1120
#define PY_METHOD(cls, name, op, args, result, name_rule, on_expr, kw0, kw1, \
1121
                  err, doc)                                                  \
1122
    API_PICK_##cls(core::api::row_id(#cls, #name), #name, args, doc)
1123
#include <dftracer/utils/python/core/api.def>
1124
    {nullptr, nullptr, 0, nullptr}};
1125

1126
PySequenceMethods Series_as_sequence = {};
1127
PyNumberMethods Series_as_number = {};
1128
PyBufferProcs Series_as_buffer = {};
1129

1130
PyGetSetDef Series_getset[] = {
1131
    {"type", Series_get_type, nullptr, "TypeId code.", nullptr},
1132
    {"length", Series_get_length, nullptr, "Row count.", nullptr},
1133
    {"null_count", Series_get_null_count, nullptr, "Null row count.", nullptr},
1134
    {"encoding", Series_get_encoding, nullptr, "Encoding code.", nullptr},
1135
    {"time_unit", Series_get_time_unit, nullptr,
1136
     "dftu_time_unit code of a Timestamp / Time / Duration column (0 s, 1 "
1137
     "ms, 2 us, 3 ns).",
1138
     nullptr},
1139
    {"timezone", Series_get_timezone, nullptr,
1140
     "Zone name of a Timestamp column; '' for a naive one or another type.",
1141
     nullptr},
1142
    {"_decimal", Series_get_decimal, nullptr,
1143
     "(precision, scale) of a Decimal column; (0, 0) for another type.",
1144
     nullptr},
1145
    {"_fixed_size", Series_get_fixed_size, nullptr,
1146
     "Width of a FixedSizeBinary column or items per row of a FixedSizeList; "
1147
     "0 for another type.",
1148
     nullptr},
1149
    {"name", Series_get_name, Series_set_name,
1150
     "The name of the Series, None when it has none. Ops keep it as pandas "
1151
     "does: an elementwise or transform op gives the result this name, a "
1152
     "binary op between two Series keeps it only when both names are equal. "
1153
     "A frame column holds the name of its column. Assigning renames this "
1154
     "Series in place (a str or None); the values stay shared.",
1155
     nullptr},
1156
    {"nbytes", Series_get_nbytes, nullptr,
1157
     "Bytes held by the column's buffers, children included.", nullptr},
1158
    {"is_json", Series_get_is_json, nullptr,
1159
     "Whether this String column holds canonical JSON text per value.",
1160
     nullptr},
1161
    {nullptr, nullptr, nullptr, nullptr, nullptr}};
1162

1163
}  // namespace
1164

1165
}  // namespace dftracer::utils::python::frame::series_detail
1166

1167
namespace dftracer::utils::python::frame {
1168

1169
TypeBinding series_binding() {
884 ✔
1170
    return {"Series", &series_detail::SeriesType,
884 ✔
1171
            &series_detail::g_series_type};
442 ✔
1172
}
1173

1174
PyObject* wrap_vec_column(dftracer::utils::dataframe::Series&& col) {
216,154 ✔
1175
    return series_detail::make_series(std::move(col));
216,154 ✔
1176
}
1177

1178
const dftracer::utils::dataframe::Series* unwrap_vec_column(PyObject* o) {
216,740 ✔
1179
    if (!PyObject_TypeCheck(o, &series_detail::SeriesType)) return nullptr;
216,740 ✔
1180
    return &reinterpret_cast<series_detail::SeriesObject*>(o)->col;
214,449 ✔
1181
}
108,513 ✔
1182

UNCOV
1183
dftracer::utils::dataframe::Series column_from_arrow(PyObject* arrow_array) {
×
UNCOV
1184
    return series_detail::import_arrow_column(arrow_array);
×
1185
}
1186

1187
bool series_list_from_py(PyObject* seq, const char* what,
3,823 ✔
1188
                         dstd::Vector<dataframe::Series>& out) {
1189
    PyObject* fast = PySequence_Fast(seq, what);
3,823 ✔
1190
    if (!fast) return false;
3,823 !
1191
    const Py_ssize_t n = PySequence_Fast_GET_SIZE(fast);
3,823 !
1192
    out.reserve(static_cast<std::size_t>(n));
3,823 ✔
1193
    for (Py_ssize_t i = 0; i < n; ++i) {
7,720 !
1194
        const dataframe::Series* s =
5,917 !
1195
            unwrap_vec_column(PySequence_Fast_GET_ITEM(fast, i));
3,897 !
1196
        if (!s) {
3,897 ✔
1197
            PyErr_SetString(PyExc_TypeError, what);
×
1198
            Py_DECREF(fast);
×
1199
            return false;
×
1200
        }
1201
        out.push_back(s->share());
3,897 !
1202
    }
2,020 !
1203
    Py_DECREF(fast);
5,663 !
1204
    return true;
1,983 ✔
1205
}
1,983 ✔
1206

1207
bool row_indices_from_py(PyObject* obj, const char* what,
11,483 ✔
1208
                         dataframe::Series& holder,
1209
                         dstd::Vector<std::int64_t>& parsed,
1210
                         dstd::Span<const std::int64_t>& out) {
1211
    const dataframe::Series* column = unwrap_vec_column(obj);
11,483 ✔
1212
    if (column && column->type() == dataframe::TypeId::Int64 &&
16,118 !
1213
        column->null_count() == 0) {
9,270 !
1214
        holder = column->materialize();
9,270 !
1215
        out = dstd::Span<const std::int64_t>(
18,540 ✔
1216
            holder.data<std::int64_t>(),
4,635 ✔
1217
            static_cast<std::size_t>(holder.length()));
9,270 ✔
1218
        return true;
9,270 ✔
1219
    }
1220
    if (!core::parse_int_seq(obj, what, parsed)) return false;
2,213 !
1221
    out = dstd::Span<const std::int64_t>(parsed.data(), parsed.size());
2,213 ✔
1222
    return true;
2,213 ✔
1223
}
5,813 ✔
1224

1225
namespace {
1226

1227
PyObject* int_list(dstd::Span<const std::int64_t> v) {
3,094 ✔
1228
    PyObject* list = PyList_New(static_cast<Py_ssize_t>(v.size()));
3,094 ✔
1229
    if (!list) return nullptr;
3,094 !
1230
    for (std::size_t i = 0; i < v.size(); ++i) {
51,724,932 !
1231
        PyObject* n = PyLong_FromLongLong(v[i]);
51,721,838 ✔
1232
        if (!n) {
51,721,838 ✔
1233
            Py_DECREF(list);
×
1234
            return nullptr;
×
1235
        }
1236
        PyList_SET_ITEM(list, static_cast<Py_ssize_t>(i), n);
51,721,838 ✔
1237
    }
35,394,300 !
1238
    return list;
1,690 ✔
1239
}
1,690 ✔
1240

1241
}  // namespace
1242

1243
PyObject* located_to_py(dstd::Result<dataframe::Located>&& r) {
1,547 ✔
1244
    if (!r) {
1,547 !
1245
        core::set_py_error(r.error());
×
1246
        return nullptr;
×
1247
    }
1248
    PyObject* positions = int_list(r->positions);
1,547 ✔
1249
    PyObject* missing = positions ? int_list(r->missing) : nullptr;
2,249 ✔
1250
    if (!missing) {
1,547 ✔
1251
        Py_XDECREF(positions);
×
1252
        return nullptr;
×
1253
    }
1254
    return Py_BuildValue("NN", positions, missing);
1,547 ✔
1255
}
845 ✔
1256

1257
PyObject* label_span_to_py(dstd::Result<dataframe::LabelSpan>&& r) {
200 ✔
1258
    if (!r) {
200 ✔
1259
        core::set_py_error(r.error());
42 ✔
1260
        return nullptr;
42 ✔
1261
    }
1262
    return Py_BuildValue("LL", static_cast<long long>(r->offset),
316 ✔
1263
                         static_cast<long long>(r->length));
237 ✔
1264
}
100 ✔
1265

1266
int init_series(PyObject* m) {
218 ✔
1267
    using namespace series_detail;
109 ✔
1268
    SeriesType = {};
218 ✔
1269
    SeriesType.ob_base = {PyObject_HEAD_INIT(nullptr) 0};
218 ✔
1270
    SeriesType.tp_name = "dftracer.utils.dftracer_utils_ext.Series";
218 ✔
1271
    SeriesType.tp_basicsize = sizeof(SeriesObject);
218 ✔
1272
    SeriesType.tp_weaklistoffset = WEAKLIST_OFFSET;
218 ✔
1273
    SeriesType.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
218 ✔
1274
    SeriesType.tp_doc = "Native columnar Series (SIMD ops + Arrow capsule).";
218 ✔
1275
    SeriesType.tp_dealloc = reinterpret_cast<destructor>(Series_dealloc);
218 ✔
1276
    Series_as_sequence.sq_length = Series_length_sq;
218 ✔
1277
    SeriesType.tp_as_sequence = &Series_as_sequence;
218 ✔
1278
    Series_as_number.nb_add = Series_nb_add;
218 ✔
1279
    Series_as_number.nb_subtract = Series_nb_sub;
218 ✔
1280
    Series_as_number.nb_multiply = Series_nb_mul;
218 ✔
1281
    Series_as_number.nb_true_divide = Series_nb_true_divide;
218 ✔
1282
    Series_as_number.nb_floor_divide = Series_nb_floor_divide;
218 ✔
1283
    Series_as_number.nb_remainder = Series_nb_remainder;
218 ✔
1284
    Series_as_number.nb_power = Series_nb_power;
218 ✔
1285
    SeriesType.tp_as_number = &Series_as_number;
218 ✔
1286
    SeriesType.tp_richcompare = Series_richcompare;
218 ✔
1287
    Series_as_buffer.bf_getbuffer = Series_getbuffer;
218 ✔
1288
    Series_as_buffer.bf_releasebuffer = Series_releasebuffer;
218 ✔
1289
    SeriesType.tp_as_buffer = &Series_as_buffer;
218 ✔
1290
    SeriesType.tp_methods = Series_methods;
218 ✔
1291
    SeriesType.tp_getset = Series_getset;
218 ✔
1292
    // Created by the kernels and the _series_from_* functions; the Python
1293
    // subclass builds one from Python data in its own __new__.
1294
    SeriesType.tp_new = nullptr;
218 ✔
1295
    if (register_type(m, &SeriesType, "Series") < 0) return -1;
218 !
1296
    ValuesType = {};
218 ✔
1297
    ValuesType.ob_base = {PyObject_HEAD_INIT(nullptr) 0};
218 ✔
1298
    ValuesType.tp_name = "dftracer.utils.dftracer_utils_ext._SeriesValues";
218 ✔
1299
    ValuesType.tp_basicsize = sizeof(ValuesObject);
218 ✔
1300
    ValuesType.tp_flags = Py_TPFLAGS_DEFAULT;
218 ✔
1301
    ValuesType.tp_dealloc = reinterpret_cast<destructor>(Values_dealloc);
218 ✔
1302
    Values_as_buffer.bf_getbuffer = Values_getbuffer;
218 ✔
1303
    ValuesType.tp_as_buffer = &Values_as_buffer;
218 ✔
1304
    if (PyType_Ready(&ValuesType) < 0) return -1;
218 !
1305
    if (init_accessors(m) < 0) return -1;
218 !
1306
    if (init_windows(m) < 0) return -1;
218 !
1307

1308
    static PyMethodDef api_rows_def = {
109 ✔
1309
        "_api_rows",
1310
        [](PyObject*, PyObject*) { return core::api::rows_as_tuple(); },
110 ✔
1311
        METH_NOARGS,
1312
        "_api_rows() -> the rows of api.def: (class, name, op, args, result, "
1313
        "name_rule, on_expr, keywords, doc)."};
1314
    PyObject* api_rows_fn = PyCFunction_NewEx(&api_rows_def, nullptr, nullptr);
218 ✔
1315
    if (!api_rows_fn) return -1;
218 !
1316
    if (PyModule_AddObject(m, "_api_rows", api_rows_fn) < 0) {
218 ✔
1317
        Py_DECREF(api_rows_fn);
×
1318
        return -1;
×
1319
    }
1320

1321
    static PyMethodDef from_arrow_def = {
109 ✔
1322
        "_series_from_arrow", vec_from_arrow, METH_O,
1323
        "_series_from_arrow(arrow_array) -> Series: import a pyarrow array "
1324
        "into a native columnar Series."};
1325
    PyObject* fn = PyCFunction_NewEx(&from_arrow_def, nullptr, nullptr);
218 ✔
1326
    if (!fn) return -1;
218 !
1327
    if (PyModule_AddObject(m, "_series_from_arrow", fn) < 0) {
218 ✔
1328
        Py_DECREF(fn);
×
1329
        return -1;
×
1330
    }
1331

1332
    static PyMethodDef from_list_def = {
109 ✔
1333
        "_series_from_list", vec_from_list, METH_VARARGS,
1334
        "_series_from_list(values[, type_id]) -> Series: a column from a list "
1335
        "of bool, int, float, str, bytes, datetime, date, time, timedelta or "
1336
        "Decimal (None is null), typed `type_id` when given; TypeError "
1337
        "otherwise."};
1338
    PyObject* list_fn = PyCFunction_NewEx(&from_list_def, nullptr, nullptr);
218 ✔
1339
    if (!list_fn) return -1;
218 !
1340
    if (PyModule_AddObject(m, "_series_from_list", list_fn) < 0) {
218 ✔
1341
        Py_DECREF(list_fn);
×
1342
        return -1;
×
1343
    }
1344

1345
    static PyMethodDef nulls_def = {
109 ✔
1346
        "_series_nulls", series_nulls, METH_VARARGS,
1347
        "_series_nulls(type_id, n) -> Series: a column of `n` nulls of that "
1348
        "type."};
1349
    PyObject* nulls_fn = PyCFunction_NewEx(&nulls_def, nullptr, nullptr);
218 ✔
1350
    if (!nulls_fn) return -1;
218 !
1351
    if (PyModule_AddObject(m, "_series_nulls", nulls_fn) < 0) {
218 ✔
1352
        Py_DECREF(nulls_fn);
×
1353
        return -1;
×
1354
    }
1355

1356
    static PyMethodDef number_rows_def = {
109 ✔
1357
        "_number_rows", number_rows, METH_VARARGS,
1358
        "_number_rows(keys, sorted) -> (ids, first): the number of each row of "
1359
        "the key columns (a null equals a null) and the first row of each "
1360
        "number; by first appearance, or by ascending value with `sorted`."};
1361
    PyObject* number_rows_fn =
327 ✔
1362
        PyCFunction_NewEx(&number_rows_def, nullptr, nullptr);
218 ✔
1363
    if (!number_rows_fn) return -1;
218 !
1364
    if (PyModule_AddObject(m, "_number_rows", number_rows_fn) < 0) {
218 ✔
1365
        Py_DECREF(number_rows_fn);
×
1366
        return -1;
×
1367
    }
1368

1369
    static PyMethodDef unstack_positions_def = {
109 ✔
1370
        "_unstack_positions", unstack_positions, METH_VARARGS,
1371
        "_unstack_positions(rows, cols, row_count, col_count) -> Series: the "
1372
        "row that fills each cell of an unstack, column by column, -1 for "
1373
        "none; "
1374
        "ValueError when two rows fill one cell."};
1375
    PyObject* unstack_positions_fn =
327 ✔
1376
        PyCFunction_NewEx(&unstack_positions_def, nullptr, nullptr);
218 ✔
1377
    if (!unstack_positions_fn) return -1;
218 !
1378
    if (PyModule_AddObject(m, "_unstack_positions", unstack_positions_fn) < 0) {
218 ✔
1379
        Py_DECREF(unstack_positions_fn);
×
1380
        return -1;
×
1381
    }
1382

1383
    static PyMethodDef unstack_columns_def = {
109 ✔
1384
        "_unstack_columns", unstack_columns, METH_VARARGS,
1385
        "_unstack_columns(values, positions, row_count) -> list of Series: "
1386
        "the columns of an unstack, null where a cell has no row."};
1387
    PyObject* unstack_columns_fn =
327 ✔
1388
        PyCFunction_NewEx(&unstack_columns_def, nullptr, nullptr);
218 ✔
1389
    if (!unstack_columns_fn) return -1;
218 !
1390
    if (PyModule_AddObject(m, "_unstack_columns", unstack_columns_fn) < 0) {
218 ✔
1391
        Py_DECREF(unstack_columns_fn);
×
1392
        return -1;
×
1393
    }
1394

1395
    static PyMethodDef tz_path_def = {
109 ✔
1396
        "_tz_set_search_path", tz_set_search_path, METH_O,
1397
        "_tz_set_search_path(paths) -> None: the directories (separated by "
1398
        "':') searched first for time zone files."};
1399
    PyObject* tz_path_fn = PyCFunction_NewEx(&tz_path_def, nullptr, nullptr);
218 ✔
1400
    if (!tz_path_fn) return -1;
218 !
1401
    if (PyModule_AddObject(m, "_tz_set_search_path", tz_path_fn) < 0) {
218 ✔
1402
        Py_DECREF(tz_path_fn);
×
1403
        return -1;
×
1404
    }
1405

1406
    static PyMethodDef retype_def = {
109 ✔
1407
        "_series_retype", series_retype, METH_VARARGS,
1408
        "_series_retype(series, type_id[, unit, timezone, precision, scale, "
1409
        "width]) -> Series: the same buffers read as another type of the "
1410
        "same width."};
1411
    PyObject* retype_fn = PyCFunction_NewEx(&retype_def, nullptr, nullptr);
218 ✔
1412
    if (!retype_fn) return -1;
218 !
1413
    if (PyModule_AddObject(m, "_series_retype", retype_fn) < 0) {
218 ✔
1414
        Py_DECREF(retype_fn);
×
1415
        return -1;
×
1416
    }
1417
    static PyMethodDef list_of_def = {
109 ✔
1418
        "_series_list_of", series_list_of, METH_VARARGS,
1419
        "_series_list_of(values, ends) -> a List Series whose row i is "
1420
        "values[ends[i - 1]:ends[i]] (the first row starts at 0); ends is a "
1421
        "non-decreasing Int64 column."};
1422
    PyObject* list_of_fn = PyCFunction_NewEx(&list_of_def, nullptr, nullptr);
218 ✔
1423
    if (!list_of_fn) return -1;
218 !
1424
    if (PyModule_AddObject(m, "_series_list_of", list_of_fn) < 0) {
218 ✔
1425
        Py_DECREF(list_of_fn);
×
1426
        return -1;
×
1427
    }
1428
    static PyMethodDef from_bytes_def = {
109 ✔
1429
        "_series_from_bytes", series_from_bytes, METH_O,
1430
        "_series_from_bytes(bytes) -> Series written by Series.to_bytes."};
1431
    PyObject* bytes_fn = PyCFunction_NewEx(&from_bytes_def, nullptr, nullptr);
218 ✔
1432
    if (!bytes_fn) return -1;
218 !
1433
    if (PyModule_AddObject(m, "_series_from_bytes", bytes_fn) < 0) {
218 ✔
1434
        Py_DECREF(bytes_fn);
×
1435
        return -1;
×
1436
    }
1437

1438
    static PyMethodDef from_dictionary_def = {
109 ✔
1439
        "_series_from_dictionary", series_from_dictionary, METH_VARARGS,
1440
        "_series_from_dictionary(codes, values) -> Series: a dictionary column "
1441
        "over a flat Int32 `codes` column (buffer shared; a null or negative "
1442
        "code is a null row) and `values` (shared); ValueError for a code "
1443
        "past the values."};
1444
    PyObject* dictionary_fn =
327 ✔
1445
        PyCFunction_NewEx(&from_dictionary_def, nullptr, nullptr);
218 ✔
1446
    if (!dictionary_fn) return -1;
218 !
1447
    if (PyModule_AddObject(m, "_series_from_dictionary", dictionary_fn) < 0) {
218 ✔
NEW
1448
        Py_DECREF(dictionary_fn);
×
NEW
1449
        return -1;
×
1450
    }
1451

1452
    static PyMethodDef from_numpy_def = {
109 ✔
1453
        "_series_from_numpy", vec_from_numpy, METH_VARARGS,
1454
        "_series_from_numpy(array[, mask]) -> Series: import a 1-D "
1455
        "C-contiguous numeric, float16 or bool numpy array (buffer protocol; "
1456
        "numbers borrow the memory, no pyarrow); `mask` is a bool array, true "
1457
        "where null."};
1458
    PyObject* np_fn = PyCFunction_NewEx(&from_numpy_def, nullptr, nullptr);
218 ✔
1459
    if (!np_fn) return -1;
218 !
1460
    if (PyModule_AddObject(m, "_series_from_numpy", np_fn) < 0) {
218 ✔
1461
        Py_DECREF(np_fn);
×
1462
        return -1;
×
1463
    }
1464
    return 0;
109 ✔
1465
}
109 ✔
1466

1467
}  // namespace dftracer::utils::python::frame
1468

1469
PyTypeObject* dftracer::utils::python::core::NativeTraits<
5,405,664 ✔
1470
    dftracer::utils::dataframe::Series>::type() {
5,405,754 ✔
1471
    return &dftracer::utils::python::frame::series_detail::SeriesType;
10,811,418 ✔
1472
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc