- 数据分析
- 数据工程
- 机器学习
【免费下载链接】cudf
cuDF - GPU DataFrame Library
导读
cudf.Series是 cuDF(RAPIDS GPU DataFrame 库)中与 pandasSeries一一对应的一维 GPU 数组结构,也是cudf.DataFrame的"列"基础单元。本文以 docs/cudf/source/cudf/api_docs/series.rst 的官方 API 索引为骨架,系统梳理Series的构造函数、属性(Attributes)、转换(Conversion)、索引与迭代(Indexing/iteration)、二元运算、统计计算、缺失值处理、重排排序、时间序列以及dt/str/cat/list/struct五大类型专属 Accessor,并结合 python/cudf/cudf/core/series.py 与 python/cudf/cudf/core/accessors/ 的源码实现说明底层原理。读完本文,你将能按类别定位cudf.Series的全部公开方法,理解其与 pandas 的兼容策略、GPU 内核调用路径,以及如何针对日期、字符串、类别、列表和结构体数据写出正确的加速代码。
Series 是什么:一维 GPU 数组
在 cuDF 中,Series被定义为一个"一维 GPU 数组(包括时间序列)"(见 series.py 中类文档字符串):
- 标签(index)不必唯一,但必须是可哈希(hashable)类型;
- 同时支持基于整数位置(
iloc)和基于标签(loc)的索引; - 来自
ndarray的统计方法被重写为自动排除缺失数据(缺失值当前以 null/NaN 表示); - 两个
Series之间的算术运算(+、-、/、*、**)会按索引值自动对齐,两者长度不必相同,结果索引为两个索引的排序并集; Series对象天然作为DataFrame的列存在。
Series的继承关系为Series(SingleColumnFrame, IndexedFrame),其构造参数与 pandas 高度一致:data(array-like、Iterable、dict 或标量)、index(1 维 array-like 或 Index,缺省为RangeIndex)、dtype(str、numpy.dtype或 ExtensionDtype)、name、copy(默认 False,仅对 Series 或 1 维 ndarray 输入生效),以及 cuDF 特有参数nan_as_null(默认 True,将np.nan转为 null;设为 False 时保留np.nan)。
核心属性(Attributes):Axes 与元数据
Series的"Axes"属性组与 pandas 语义对齐,是日常最常用的一组 API:
| 属性 | 说明 |
|---|---|
index/axes | 轴标签,axes返回轴列表 |
values/dtype/dtypes | 底层数据视图与数据类型 |
shape/ndim/size | 形状((n,))、维数(恒为 1)、元素个数 |
name | Series 名称 |
T | 转置(一维 Series 转置即自身) |
empty | 是否为空 |
null_count/valid_count/has_nulls | null 数量、有效值数量、是否含 null |
hasnans | 是否存在 NaN |
memory_usage | 内存占用(字节) |
其中memory_usage(index=True, deep=False)在 series.py#L1158 实现,与 pandas 保持一致的签名:默认统计索引与数据的总内存,deep=True时深入统计对象类型元素的实际内存。
Series.at、Series.iat是标量访问入口(分别按标签/位置取单个值),Series.loc、Series.iloc则是切片与花式索引入口。从源码结构看(series.py#L181 与 series.py#L281),iloc内部经由indexing_utils.parse_row_iloc_indexer解析索引规格后调用统一的_getitem_preprocessed执行;loc在布尔 Series 作为索引器时会先做索引对齐(arg.reindex(self._frame.index)),标签不存在时会抛出KeyError并列出缺失标签,这与 pandas 行为一致。
转换(Conversion):生态互操作
Series提供两条主线转换能力:
类型转换:astype(dtype)按需转换列类型;convert_dtypes推断并转换为最佳类型;copy复制对象。
跨生态转换:to_pandas、to_numpy、to_list/tolist、to_arrow、to_cupy(CuPy 数组)、to_dlpack(DLPack 协议)、to_dict、to_frame(转为单列 DataFrame)、to_string,以及to_hdf/to_json等输出;反向有类方法from_arrow。__array__协议使cudf.Series可被numpy.asarray等直接消费。scale用于十进制定点类型。序列化族包括serialize/deserialize、host_serialize/host_deserialize、device_serialize/device_deserialize,以及与 pylibcudf 的双向转换to_pylibcudf/from_pylibcudf。
以to_pandas(index=True, nullable=False, arrow_type=False)为例(series.py#L2078):index=False时结果使用默认索引;nullable=True时尽可能产出 pandas 可空扩展类型;arrow_type=True时返回pandas.ArrowDtype;二者不能同时为True。这类方法让 cuDF 与 pandas、NumPy、PyArrow、CuPy 生态可以无缝互转。
索引与迭代(Indexing & Iteration)
该组提供loc/iloc之外的高层操作:
__iter__:按行迭代;items/iteritems:产出 (index, value) 对;keys:返回索引视图;squeeze:若维度可压缩则压缩为标量。
二元运算符(Binary Operators):与 pandas 对齐的运算族
Series完整实现了 pandas 风格的算术与比较运算符,包含正向与反向(r 前缀)版本:
- 算术:
add/radd、sub/subtract/rsub、mul/multiply/rmul、truediv/div/divide/rtruediv/rdiv、floordiv/rfloordiv、mod/rmod、pow/rpow,以及round; - 比较:
lt、gt、le、ge、ne、eq; - 聚合:
product、dot(向量点积)。
这些方法在 cuDF 中最终由 C++/CUDA 层的 libcudf binary operation 内核在 GPU 上并行执行;对Series间的运算,cuDF 会先按索引对齐再做元素级计算。反向版本(r前缀)支持"标量在左、Series 在右"的运算写法,例如10 - series。
函数应用、GroupBy 与窗口
apply:逐元素应用 Python 函数(配合 Numba/CUDA UDF 可获得 GPU 加速);map:按映射关系转换元素(等价 pandasSeries.map);groupby:返回SeriesGroupBy对象(源码中通过_groupby = SeriesGroupBy绑定,见 series.py#L491),支持聚合、变换与多级分组;rolling:滚动窗口计算;pipe:函数管道串联,便于链式调用。
计算与描述性统计(Computations / descriptive stats)
这是Series使用频率最高的一组,覆盖:
- 基础聚合:
count、sum/prod、mean、median、min、max、mode、var、std、skew、kurt/kurtosis、quantile、describe; - 逻辑/归约:
all、any; - 累积运算:
cumsum、cumprod、cummin、cummax; - 差分/变化率:
diff、pct_change、autocorr、corr、cov; - 排序/唯一性:
rank、nlargest、nsmallest、unique、nunique、is_unique、is_monotonic_increasing、is_monotonic_decreasing、value_counts; - 其他:
abs、clip、between、digitize、factorize、ewm(指数加权窗口)。
其中describe(series.py#L3532)与 pandas 一样按 dtype 分支输出不同统计摘要;统计方法默认排除 null/NaN(与类文档所述"统计方法自动排除缺失数据"一致)。value_counts、unique等在底层调用 libcudf 的哈希/排序内核完成 GPU 并行去重与计数。
重索引、选择与标签操作
add_prefix/add_suffix:为索引批量添加前后缀;drop:按标签删除;drop_duplicates/duplicated:去重与重复标记;equals:元素级全等比较;head/tail:取首/尾 n 个元素;isin:成员判断;reindex:按新索引重排(自动对齐);rename:重命名 Series(或索引);reset_index:将索引重置为 RangeIndex;sample:随机抽样;take:按位置数组取值;tile:沿轴平铺重复;truncate:按标签范围截断;where/mask:条件保留/遮蔽(where保留满足条件者,mask相反)。
缺失数据处理(Missing data handling)
cuDF 的缺失值用 null(对应 pandas NaN)表示,该组 API 提供完整的缺失值治理:
isna/isnull(等价)与notna/notnull:缺失检测,返回布尔 Series;dropna:删除含缺失的行;fillna:填充缺失值(标量或前向/后向填充);ffill/bfill:前向/后向填充;interpolate:插值;replace:值替换;nans_to_nulls:cuDF 特有方法,将np.nan显式转换为 null。
cuDF 的列在 GPU 上通过独立的有效性掩码(validity mask / null mask)表示缺失,因此 null 检测与填充在内核层面高效并行。
重塑与排序(Reshaping, sorting)
argsort:返回排序索引;sort_values:按值排序;sort_index:按索引排序;explode:将列表/结构体元素展开为多行;searchsorted:有序序列中查找插入位置;repeat:重复元素;transpose:转置。
合并与时间序列(Combining / Time Series)
合并组仅有一个方法update(用另一序列就地更新重叠位置);时间序列组包含shift(移位)与resample(重采样,绑定SeriesResampler,见 series.py#L492)。
元数据:attrs / flags
attrs:自定义元数据字典;flags/set_flags:行为标志(如是否允许链式赋值)。
五大类型专属 Accessor
pandas 风格地把 dtype 专属方法放入独立命名空间,Series通过注册机制挂载五个 Accessor(对应文档中的对照表):
| 数据类型 | Accessor |
|---|---|
| Datetime / Timedelta | Series.dt |
| String | Series.str |
| Categorical | Series.cat |
| List | Series.list |
| Struct | Series.struct |
在源码中,这些 Accessor 均继承自 base_accessor.py 的BaseAccessor,内部持有父对象self._parent与底层列self._column,并通过_return_or_inplace统一处理"返回新对象"与"就地修改"两种语义——就地模式调用_mimic_inplace更新父对象列。
Series.dt:日期时间与时间差属性
文档明确指出Series.dt用于以 datetimelike 方式访问 Series 值并返回多个属性,调用形式为Series.dt.<property>。其实现类为 series.py#L4114 的DatetimeProperties与 series.py#L5238 的TimedeltaProperties,两者均继承BaseDatelikeProperties。
Datetime 属性:year、month、day、hour、minute、second、microsecond、nanosecond、dayofweek/weekday、dayofyear/day_of_year、quarter、is_month_start、is_month_end、is_quarter_start、is_quarter_end、is_year_start、is_year_end、is_leap_year、days_in_month。
Datetime 方法:isocalendar、strftime、round、floor、ceil、tz_localize。
Timedelta 属性:days、seconds、microseconds、nanoseconds、components。
从源码看,属性实现遵循统一模式——例如dt.year返回self._return_result_like_self(self.series._column.year)(series.py#L4187),即调用底层列的 GPU 内核方法后包装回 Series;dt.weekday的结果 dtype 为int16,而 timedelta 系列的days/seconds/microseconds结果为int64。components会返回一个多列 DataFrame(days/hours/minutes/seconds/milliseconds/microseconds/nanoseconds)。文档自带的示例展示了pd.date_range构造后提取second、hour、weekday,以及 timedelta 系列上components/days/seconds/microseconds的典型用法。
Series.str:GPU 向量化字符串处理
StringMethods(accessors/string.py#L74)模仿 pandas 的df.str接口,文档注明"nulls stay null(除非特定方法另行处理)",并借鉴 Python 字符串方法与 R 的 stringr 包。该 Accessor 方法极其丰富,按功能可划分为:
- 大小写/排版:
capitalize、lower、upper、swapcase、title、center、ljust、rjust、pad、wrap、zfill; - 查找/匹配:
contains、match、find、rfind、findall、find_multiple、index、rindex、count、endswith、startswith、like、extract、get_json_object; - 切分/合并:
split、rsplit、split_part、partition、rpartition、cat、join、slice、slice_from、slice_replace、insert、repeat、get; - 替换/清理:
replace、replace_tokens、replace_with_backrefs、translate、strip、lstrip、rstrip、removeprefix、removesuffix、normalize_spaces; - 类型判断:
isalnum、isalpha、isdecimal、isdigit、isfloat、ishex、isinteger、isipv4、isspace、islower、isnumeric、isupper、istimestamp、istitle、isempty、is_consonant、is_vowel; - 编码/转换:
byte_count、code_points、hex_to_int/htoi、ip2int/ip_to_int、url_decode、url_encode; - NLP 与文本挖掘:
character_ngrams、character_tokenize、detokenize、edit_distance、jaccard_index、minhash、ngrams、ngrams_tokenize、token_count、tokenize、filter_alphanum、filter_characters、filter_tokens、porter_stemmer_measure; - 其他:
len。
实现层面(见 string.py 头部),字符串参数会被规范化为pylibcudfScalar 或StringColumn;正则相关方法仅支持re.MULTILINE | re.DOTALL | re.IGNORECASE组合标志(_is_supported_regex_flags),其余标志会被拒绝,这是与 pandas 正则行为的一个重要差异。这些方法最终映射到 libcudf 的 C++ 字符串内核(源码位于 cpp/src/strings/),在 GPU 上并行处理全部字符串。
Series.cat:类别数据操作
CategoricalAccessor(accessors/categorical.py#L17)提供类别专属操作:
- 属性:
categories(返回Index,见 categorical.py#L81)、ordered(是否有序)、codes(整数编码 Series,见 categorical.py#L88); - 方法:
reorder_categories、add_categories、remove_categories、set_categories、as_ordered、as_unordered。
类别数据在底层以"类别字典 + 整数编码列"存储,因此codes与categories的读写非常轻量。
Series.list:列表类型操作
ListMethods(accessors/lists.py#L25)面向 list 嵌套类型:
astype(列表内元素类型转换)、concat(拼接)、contains(成员判断)、index(查找元素首次出现位置)、get(按位置取子元素)、leaves(展平为叶元素列)、len(每行长度)、sort_values(行内排序)、take(按位置取子集)、unique(行内去重)。
Series.struct:结构体类型操作
StructMethods(accessors/struct.py#L18)仅两个方法:field(按字段名提取子列)与explode(展开结构体为多列)。
序列化 / IO / 转换(Serialization / IO / conversion)
该组与"转换"组互补,聚焦序列化与 IO 输出:to_arrow、to_cupy、to_dict、to_dlpack、to_frame、to_hdf、to_json、to_numpy、to_pandas、to_string,以及hash_values(GPU 哈希)与 pylibcudf 互转to_pylibcudf/from_pylibcudf,类方法from_arrow。其中to_pylibcudf暴露底层 pylibcudf 对象,适合需要细粒度控制的场景。
实战:快速上手示例
以下示例串起本文的核心 API(构造、dt访问器、统计、缺失值、字符串与互操作):
import cudf import pandas as pd # 1) 构造:索引对齐 + 自动 null s = cudf.Series([1, 2, None, 4], name="col") print(s.null_count) # 1 print(s.isna().sum()) # 1 # 2) 描述性统计(自动跳过 null) print(s.describe()) # 3) 二元运算按索引对齐 a = cudf.Series([1, 2, 3], index=[0, 1, 2]) b = cudf.Series([10, 20], index=[1, 2]) print((a + b)) # 索引 0 处为 NaN/NA # 4) 日期时间 Accessor dates = cudf.Series(pd.date_range("2024-01-01", periods=3, freq="D")) print(dates.dt.year) # int16 print(dates.dt.dayofweek) # 周一=0 # 5) 字符串向量化 text = cudf.Series(["Hello World", "cuDF GPU", None]) print(text.str.lower()) # 含 null 时保持 null print(text.str.contains("GPU")) # 6) 互操作 print(type(s.to_pandas())) print(type(cudf.Series.from_arrow(pd.array([1, 2, 3]).__array__())))总结:如何用好这份 API 索引
series.rst是一份"按功能分区"的 API 导航:构造器、属性、转换、索引、二元运算、函数应用、统计、重索引、缺失值、重塑排序、合并、时间序列、元数据、五大 Accessor 与序列化 IO。当你需要定位某个能力时:
- 先按数据 dtype 判断是否可用 Accessor(
dt/str/cat/list/struct); - 通用能力(统计、缺失值、排序、索引)直接查
Series本体方法; - 需要跨界互操作(pandas/NumPy/PyArrow/CuPy/DLPack/pylibcudf)时,从"转换"与"序列化/IO"两组中选择对应方法;
- 涉及正则时留意 cuDF 仅支持
re.MULTILINE | re.DOTALL | re.IGNORECASE三种标志。
所有方法在 python/cudf/cudf/core/series.py 与 python/cudf/cudf/core/accessors/ 中均有可直接阅读的 docstring 与实现,libcudf 内核层可进一步在 cpp/src/strings/ 等目录深入研读。
- 数据分析
- 数据工程
- 机器学习
【免费下载链接】cudf
cuDF - GPU DataFrame Library
相关推荐
cuDF Index 对象 API 全解析:从 Index 基类到 MultiIndex 与 DatetimeIndex 的 GPU 加速索引体系
cuDF Index 对象 API 全解析:从 Index 基类到 MultiIndex 与 DatetimeIndex 的 GPU 加速索引体系 导读 本文基
数据分析数据工程机器学习ioredis 命令支持实现指南:从元数据到生成器、测试与验证的完整工作流
ioredis 命令支持实现指南:从元数据到生成器、测试与验证的完整工作流 导读 :本文以 ioredis 仓库内的 implement command 技能文
数据分析数据工程机器学习coreos-vagrant 配置完全指南:config.rb 中 10 个必须掌握的虚拟机配置选项
coreos vagrant 配置完全指南:config.rb 中 10 个必须掌握的虚拟机配置选项 想用 Vagrant 在本地快速跑一个 Container
数据分析数据工程机器学习
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考