Skip to main content

Crate fp_types

Crate fp_types 

Source
Expand description

Foundational value-type abstractions for frankenpandas — the enums, structs, and free functions that every other crate (fp-columnar, fp-index, fp-frame, fp-io, …) consumes when representing scalar data, dtypes, missing values, and time deltas.

The types here intentionally stay tiny and dependency-light (serde, thiserror) so they can sit at the bottom of the workspace dep graph.

§Core value types

  • DType: the dtype enum — Null, Bool, Int64, Float64, Utf8, Categorical, Timedelta64, Datetime64, Period, Interval, Sparse. Drives column / series storage decisions across the workspace.
  • Scalar: the per-cell value enum, parameterized by DType. Each variant holds the actual data (Int64(i64), Float64(f64), Utf8(String), …) plus the Null(NullKind) variant for missing values.
  • NullKind: distinguishes the three pandas missing-value “flavors” — Null (Python None / SQL NULL), NaN (floating-point not-a-number), NaT (timedelta / datetime not-a-time). Scalar::Null(...) carries the kind so downstream code can preserve pandas semantics.
  • SparseDType: descriptor for sparse-encoded dtypes (paired value dtype + fill value).

§Time / duration types

§Dtype inference + casting

§Missing-value helpers

Free fns matching pd.isna / pd.notna, plus fill/drop helpers, plus the nan* aggregations (nansum, nanmean, nancount, nanmin, nanmax, nanmedian, nanvar, nanstd) that mirror pandas’ missing-aware reductions.

⚠️ Only HALF that list is a module-level pandas surface. pd.isna and pd.notna are free functions; pd.fillna and pd.dropna do NOT exist (measured 2.2.3: AttributeError on the module) – pandas exposes fill and drop only as METHODS, Series.fillna / DataFrame.dropna. The free fns here are an FP convenience, not a pandas mirror.

§Error reporting

Errors are explicit enums via thiserror: TypeError for dtype-related failures (incompatible-cast, no-common-dtype) and TimedeltaError for parse failures.

Re-exports§

pub use api::types::pandas_dtype;

Modules§

api
Public pandas API modules (pandas.api.*).
overflow_audit
Deterministic, opt-in audit trail for HARDENED-mode recoveries.

Structs§

CategoricalDtype
Pandas-equivalent categorical dtype descriptor (pd.CategoricalDtype).
CategoricalMetadata
HostValue
A shared handle on a HostObject.
Interval
A bounded numeric interval between two f64 endpoints.
IntervalDtype
Pandas-equivalent interval dtype descriptor (pd.IntervalDtype).
KahanSum
pandas’ compensated running sum: its cython group_sum, group_mean and group_cumsum add each float as y = v - comp; t = sum + y; comp = t - sum - y; sum = t (Kahan), comp reset to 0 where it is NaN (an inf added; GH#53606). A plain += fold differs from it in the last bits - groupby sum of ten 0.1 is 1.0 in pandas, 0.9999999999999999 naively (br-frankenpandas-xhogl).
OptionContextGuard
RAII scope guard that restores options to their prior values when dropped.
PandasReductions
pandas’ float reductions of one numeric column - sum, mean, var, std, sem, skew, kurt - adding in numpy’s exact order, so a long column answers pandas’ bits rather than a nearby value. Measured against live pandas 2.2.3 / numpy 2.3.5; bead br-frankenpandas-9iim6 holds the model and the alternatives it rejected.
Period
A single pandas-style Period value.
PeriodDtype
Pandas-equivalent period dtype descriptor (pd.PeriodDtype).
SkewMoments
pandas’ online skewness: its cython group_skew folds each float into running moments (delta = v - m1; delta_n = delta / n; term1 = delta * delta_n * (n - 1); m1 += delta_n; m3 += term1 * delta_n * (n - 2) - 3 * delta_n * m2; m2 += term1) and answers n * (n - 1) ** 0.5 / (n - 2) * (m3 / m2 ** 1.5) - 0 when m2 is 0, missing below 3 values - where the two-pass nanskew (Series.skew) differs in the last bits (br-frankenpandas-vjfq9).
SparseDType
TemporalFailure
A temporal overflow, naming the operation that overflowed and the pandas exception it corresponds to.
TemporalRecovery
A bounded defensive recovery that HARDENED mode performed, recorded so a run can be audited after the fact.
Timedelta
TimedeltaComponents
Timestamp
A nanosecond-precision point in time, Unix-epoch anchored.
WelfordVar
pandas’ online variance: its cython group_var folds each float as Welford (mean += (v - old) / n; m2 += (v - mean) * (v - old)) and answers m2 / (n - ddof), std its square root and sem sqrt(m2 / (n - ddof) / n) - where the two-pass form differs in the last bits (a constant group’s var is 0.0, not 1e-34; br-frankenpandas-xhogl).

Enums§

AmbiguousTime
What tz_localize does with a wall time a DST change repeats (pandas’ ambiguous=, for one value): refuse it, take its first occurrence (DST, pandas’ True) or its second (standard time, False), or make it NaT.
DType
DatetimeStringResolution
How wide astype(str) renders a datetime64[ns] value.
IntervalClosed
Endpoint-inclusion policy for an Interval.
IntervalSubtype
The type of an interval’s endpoints, pandas’ interval[int64] or interval[float64] subtype: integer endpoints print without ‘.0’ (pd.cut(s, [0, 3, 6]) is (0, 3], where float edges are (0.0, 3.0]). The endpoints themselves are f64 either way (fvsao.54).
MissingLayout
How pandas holds a column’s missing values, which decides the order its float reductions add in (br-frankenpandas-9iim6).
NonexistentTime
What tz_localize does with a wall time a DST change skips (pandas’ nonexistent=): refuse it, move it to the first instant after the gap (shift_forward) or the last nanosecond before it (shift_backward), make it NaT, or move the wall time by a duration (nanoseconds) and localize that.
NullKind
NumericWidth
A numpy numeric dtype narrower than the 64-bit storage a column keeps its values in: pandas’ int8 / int16 / int32, uint8 / uint16 / uint32 / uint64 and float32, and over a nullable column the masked Int8 … UInt64 / Float32 (fvsao.23).
NumpyNumeric
A numeric column’s numpy dtype as numpy’s promotion sees it: kind and bits. The 64-bit ones are a column without a NumericWidth.
ObjectValue
A pandas object cell that is not one of Scalar’s value kinds: a list, or a value of the host language (a Python datetime.date, dict, numpy dtype) that the core carries without reading (fvsao.33).
OptionError
Error encountered when inspecting or modifying configuration options.
OptionValue
Represents a configuration option value, matching pandas pd.options.
OverflowPolicy
How a temporal overflow should be surfaced.
PandasDecimal
What pandas’ default text-to-float64 conversion - read_csv / read_table with float_precision=None or 'high', and to_numeric of strings - makes of a token (br-frankenpandas-py3c0).
PandasTemporalError
The pandas-side exception class a failed temporal operation corresponds to.
PeriodFreq
Period frequency code. Matches pandas offset alias core set.
ReductionValues
A numeric column’s values as pandas’ float reductions read them: one buffer or the chunks of one (a concat result), float64 or a numpy int64 array (read through numpy’s int64 -> float64 cast; ints that pandas holds as float64 because one is missing are Float).
Scalar
TimeZoneError
Why a time-zone conversion failed, as pandas (pytz) classifies it.
TimedeltaError
TimedeltaStringResolution
How astype(str) renders a timedelta64[ns] COLUMN.
TypeError

Constants§

NA
Pandas pd.NA singleton representing missing data in nullable dtypes.
NAT
Pandas pd.NaT singleton representing Not-a-Time in datetime/timedelta data.
NaT
Alias for NAT matching pandas capitalization pd.NaT.

Traits§

AsDType
Trait for types that carry or represent a DType.
HostObject
A host-language value an object cell carries - the Python binding’s objects: compared and printed by the host itself.

Functions§

cast_scalar
Cast a scalar reference to a target dtype (clones only when conversion is needed).
cast_scalar_owned
Cast a scalar to a target dtype, taking ownership to avoid redundant clones when the value already has the correct type (AG-03: identity-cast skip).
common_dtype
count_na
declare_host_lock
Declare that callers into the core may hold a host lock that host objects need - the Python binding, whose every call holds the GIL, declares it when its module loads. Without it no worker is ever blocked.
describe_option
Return formatted descriptions of one or all options, matching pd.describe_option(pat).
dropna
eng_float_format
Format float values according to engineering format, matching pandas EngFormatter.
fill_na
float_to_string_for_astype
get_eng_float_format
Get the current engineering float format configuration if active.
get_option
Retrieve the current value of a configuration option, matching pd.get_option(pat).
host_values_block_workers
Whether a parallel kernel must run inline (one worker): a host value compares, hashes and prints through its host (Python), which a worker thread reaches only by taking the host’s lock (the GIL); when the thread that spawned the worker holds that lock while it waits for the worker, both wait forever - DataFrame.groupby(dates).rank() hung that way (4qg5w.13). So while any host object is alive in a process whose callers may hold that lock, kernels size themselves to one worker.
infer_dtype
interval_range
Build equal-width intervals spanning a range, matching pd.interval_range.
interval_range_by_periods
Build periods equal-width intervals spanning [start, end].
interval_range_by_step
Build equal-step-width intervals spanning [start, end].
isna
isnull
nanall
nanany
nanargmax
Position (in the original slice) of the non-missing maximum.
nanargmin
Position (in the original slice) of the non-missing minimum.
nancount
nancummax
Cumulative maximum respecting null propagation.
nancummin
Cumulative minimum respecting null propagation.
nancumprod
Cumulative product respecting null propagation.
nancumsum
nancumsum_with_policy
Matches np.nancumsum / pd.Series.cumsum(). Missing input positions pass through as Null(NaN) in the output; the running sum ignores those positions when accumulating. Cumulative sum under an explicit overflow policy.
nankurt
Excess sample kurtosis (Fisher’s definition, bias-corrected) over non-missing values.
nanmax
nanmean
nanmean_grouped
nanmean as pandas’ grouped mean: the KahanSum over the count. Temporal input keeps nanmean.
nanmedian
nanmin
nannunique
Count of unique non-missing values.
nanprod
Product of non-missing values. Returns 1.0 for empty input (matching pandas).
nanptp
Peak-to-peak range of non-missing values (max − min).
nanquantile
Linear-interpolation quantile over non-missing numeric values.
nansem
Standard error of the mean over non-missing values.
nansem_grouped
Standard error of the mean as pandas’ groupby, resample and pivot_table compute it: sqrt(var / n) (libgroupby’s group_var(name="sem")), which can differ in the last bit from nansem’s std / sqrt(n) (Series.sem): for [1.0, 4.0] this is 1.5 and nansem 1.4999999999999998 (br-frankenpandas-7hxqv). Timedelta input keeps nansem.
nanskew
Sample skewness (bias-corrected, Fisher-Pearson) over non-missing values.
nanskew_grouped
nanskew as pandas’ grouped skew: SkewMoments over the present values.
nanstd
nanstd_grouped
nanstd as pandas’ grouped std: WelfordVar. Temporal input keeps nanstd.
nansum
nansum_grouped
nansum as pandas’ groupby / resample / pivot_table add floats: the compensated KahanSum (br-frankenpandas-xhogl). Timedelta input keeps nansum’s exact integer sum.
nansum_utf8
Sum of a STRING group: pandas concatenates, skipping missing entries.
nanvar
nanvar_grouped
nanvar as pandas’ grouped var: WelfordVar. Timedelta input keeps nanvar.
notna
notnull
numpy_pairwise_sum
numpy’s pairwise_sum, the kernel of its float add.reduce over a contiguous run, every addition in T: below 8 values a running sum from 0; up to 128, eight running sums seeded with the first eight values and stepped over the 8-value blocks, folded as ((r0 + r1) + (r2 + r3)) + ((r4 + r5) + (r6 + r7)), then the remainder in order; beyond that the two halves (the first a multiple of 8 long) summed apart. pandas’ float32 and float64 sums are it bit for bit, where a sum rounded once or added left to right differs in the last place (fvsao.23, br-frankenpandas-9iim6).
numpy_pairwise_sum_by
numpy_pairwise_sum over len values that numpy reads from one array but fp holds in another shape (a cast, chunks, missing slots as 0): fill(start, block) writes values start..start + block.len() into each block, at most 128 long, the blocks asked for left to right.
option_context
Temporarily override options within a scoped context, matching pd.option_context(...).
pandas_decimal_to_f64
pandas’ default text-to-float64 conversion of token (no surrounding space). It is not correctly rounded: the first 17 digits - leading zeros count - accumulate as x * 10 + d in float64 (digits past them in the integer part raise the exponent, in the fraction they are dropped), the exponent is a wrapping 32-bit integer of at most 17 digits, and the value is scaled ONCE by a float64 power of ten: x * 1e{e} for e up to 308, x / 1e{-e} down to -308, x / 1e{-308-e} / 1e308 down to -616, +0.0 below that; past 308, or overflowing to infinity, the token is not a float. The sign applies last. Measured against live pandas 2.2.3 over 180k tokens (repr / %.20e / %.25f / 1-30 digit fractions / leading zeros / exponents to +-640 / wrapping exponents), 0 mismatches; float() misses about a third of them.
pandas_int_to_f64
An integer cell of a column pandas reads as float64 (one of its cells is fractional): the integer’s digits through pandas_decimal_to_f64, exact up to 2^53.
period_range
Build periods consecutive Periods starting at start.
python_bytes_repr
Python’s repr of a bytes value: b'...' (double quotes when it holds a ' and no "), printable ASCII as itself, \\, \t, \n, \r and the quote escaped, every other byte as \xNN.
reset_eng_float_format
Reset engineering float formatting back to default.
reset_option
Reset one or all configuration options to their defaults, matching pd.reset_option(pat).
set_eng_float_format
Set pandas-compatible engineering float formatting option. Matches pd.set_eng_float_format(accuracy=3, use_eng_prefix=False).
set_option
Set the value of a configuration option, matching pd.set_option(pat, value).
strftime_in_zone
The instant nanos formatted by strftime_python: a naive value as it is; in tz (a tz-aware value, nanos its UTC instant) on the zone’s wall clock with the offset and abbreviation of that instant.
strftime_python
wall_nanos formatted as Python’s (glibc’s) strftime does - what pandas’ Timestamp.strftime / Series.dt.strftime / to_csv(date_format=) run per value: the C-locale directives (%a %A %b %B %c %d %e %f %H %I %j %m %M %p %S %U %w %W %x %X %y %Y %z %Z %%), glibc’s (%C %D %F %g %G %h %k %l %n %P %r %R %t %T %u %V) and its - (no padding), _ (space padding), 0 and ^ (upper case) flags. An unknown directive is echoed as written, as glibc does. zone is a tz-aware value’s UTC offset (in seconds) and abbreviation at that instant, which %z / %Z print (empty for a naive value).
timestamp_text_in_zone
str(Timestamp) of the instant nanos in tz, as pandas prints a tz-aware value (repr cells, astype(str)): its wall clock ‘YYYY-MM-DD HH:MM:SS’, its own fraction when it has one (six digits, nine for nanoseconds), and the zone’s +HH:MM offset then.
tz_abbreviation
The zone’s name at the UTC instant utc_nanos as strftime('%Z') prints it: an IANA zone’s abbreviation then (‘EST’ / ‘EDT’), a fixed offset’s UTC+HH:MM (‘UTC’ for zero).
tz_canonical_name
The name pandas gives the zone tz: a fixed offset is UTC+HH:MM (‘+05:30’ and ‘UTC+05:30’ alike; a zero offset or ‘Z’ is ‘UTC’), an IANA name stays as given.
tz_offset_seconds
The UTC offset, in seconds east of UTC, that tz has at the UTC instant utc_nanos - what a tz-aware timestamp adds to its instant to show its wall clock.
tz_utc_to_wall_nanos
The wall clock the UTC instant utc_nanos shows in tz, as naive nanoseconds (NaT, i64::MIN, stays NaT).
tz_validate
Whether tz names a zone pandas accepts (‘UTC’, +HH:MM, an IANA name).
tz_wall_to_utc_nanos
The UTC instant of the wall-clock time wall_nanos in tz, as pandas’ tz_localize with ambiguous / nonexistent = ‘raise’: a wall time a DST change skips is TimeZoneError::NonExistent, one it repeats TimeZoneError::Ambiguous. NaT (i64::MIN) stays NaT.
tz_wall_to_utc_nanos_with
tz_wall_to_utc_nanos under pandas’ ambiguous / nonexistent policies; NaT (i64::MIN) where a policy says NaT.

Type Aliases§

CategoricalDType
IntervalDType
PeriodDType