拓冰建站拓冰建站
首页 / 资讯中心 / 正文

pandas API Reference 权威指南:公共 API 全景、子包划分与文档导航

pandas API Reference 权威指南公共 API 全景、子包划分与文档导航【免费下载链接】pandasFlexible and powerful data analysis / manipulation library for Python, providing labeled data structures similar to R data.frame objects, statistical functions, and much more项目地址: https://gitcode.com/gh_mirrors/pa/pandas本篇技术指南基于 pandas 官方文档的 API Reference 索引页doc/source/reference/index.rst系统梳理 pandas 公共 API 的边界、公开子包、顶层命名空间分布以及官方文档的组织结构。读完本文你将掌握哪些对象属于pandas.*公共 API、哪些模块被明确标记为私有不可依赖、如何通过pandas.api.*子包使用扩展/类型/索引器接口以及如何按 Series、DataFrame、数组与数据类型 等 18 个章节高效检索 API 文档。一、公共 API 的边界什么才是公开的pandas 的 API 面有一个非常明确的界定规则所有暴露在pandas.*命名空间中的类与函数都是公共 API。这一约定既是用户使用 pandas 的指南也是下游库与开发者担保稳定的契约。import pandas as pd # pandas.* 下的对象均为公共 API pd.DataFrame, pd.Series, pd.Index # 核心数据结构 pd.read_csv, pd.merge, pd.concat # I/O 与重塑函数 pd.Timestamp, pd.Timedelta, pd.Period # 时间标量 pd.NA, pd.isna, pd.NaT # 缺失值相关与之对应的实际定义位于仓库入口文件 pandas/init.py其中通过from pandas.core.api import ...、from pandas.io.api import ...等语句将数百个对象提升到顶层命名空间并通过__all__列表显式声明哪些名字是公共 API。从源码结构看__all__中列出的名字如DataFrame、read_parquet、cut、api、testing等与文档宣称的公共范围严格一致文档还特别注明pandas 尚未提供 py.typed 类型标注文件公共 API 正是以这套文档为准来确定的。二、公开子包总览除了顶层命名空间以下子包被官方明确列为公共 API各自承担一组职责子包职责pandas.errorspandas 抛出的自定义异常与警告类pandas.plotting绘图公共 APIpandas.testing编写涉及 pandas 对象的测试时使用的断言函数pandas.api.extensions用于扩展 pandas 对象的函数与类pandas.api.indexers滚动窗口rolling window相关的索引器pandas.api.interchangeDataFrame 交换协议DataFrame interchange protocolpandas.api.types数据类型相关的类与函数pandas.api.typing类型提示type-hinting可能需要的类其中pandas.api这个命名空间本身由 pandas/api/init.py 定义聚合了executors、extensions、indexers、interchange、internals、types、typing七个模块并同样通过__all__固定了公共面。1. pandas.errors异常与警告pandas/errors/init.py 是自定义异常/警告的聚合出口例如IntCastingNaNError将含 NaN 的数组astype为整数时抛出、NullFrequencyError对freqNone的索引执行shift时抛出、PerformanceWarning检测到可能影响性能的操作时警告此外还汇集了来自pandas._libs.tslibs的IncompatibleFrequency、OutOfBoundsDatetime、OutOfBoundsTimedelta等时间类异常。用户捕获 pandas 特有错误时应统一从pandas.errors导入而不是依赖内部模块路径。2. pandas.api.typing类型提示专用类需要注意一个容易混淆的点pandas.api.typing中的类例如pandas.api.typing.DataFrameGroupBy、pandas.api.typing.Expression是用户在类型标注中可能遇到的中间结果类型不应由用户直接实例化。官方文档特别强调不要把pandas.api.typing与pandas-stubs包中的类混为一谈——pandas-stubs是在 pandas 之外额外提供的一组类型提示类二者并非同一来源。在 general_functions.rst 中api.typing.Expression就与顶层eval函数并列被收录用于标注pd.eval的表达式类型。3. 其他子包的定位pandas.testing提供assert_frame_equal、assert_series_equal、assert_index_equal等断言工具配合 doc/source/reference/testing.rst 使用pandas.plotting聚合绘图 API对应 doc/source/reference/plotting.rstpandas.api.extensions面向库作者提供register_extension_dtype、register_dataframe_accessor、register_series_accessor、register_index_accessor等注册函数以及ExtensionDtype/ExtensionArray基类详见 doc/source/reference/extensions.rst。它还导出一个哨兵值pandas.api.extensions.no_default用于部分方法中判断用户是否传入了非默认参数必须用is比较不能直接用pandas.api.indexers提供check_array_indexer等窗口索引器校验工具pandas.api.interchange提供from_dataframe用于从其他实现 DataFrame 交换协议的库导入数据见 general_functions.rst 的 Importing from other DataFrame libraries 一节。三、必须警惕的 PRIVATE 模块文档以醒目的warning块声明pandas.core、pandas.compat顶层模块是私有的PRIVATE其中的稳定功能不提供任何保证。这意味着尽管你在源码中能看到pandas.core.frame.DataFrame这样的实现类但任何直接依赖pandas.core/pandas.compat内部结构的代码都不在兼容性担保范围内未来版本可能随时变动。撰写第三方库或长期维护的脚本时应始终经由pandas顶层或pandas.api.*公共入口调用。此外pandas.io、pandas.tseries、pandas.util这三个子模块中只有文档中明确列出的公共函数才受稳定承诺保护例如pandas.io下的read_csv等 I/O 入口、pandas.tseries下的offsets与infer_freq、pandas.util下的hash_array/hash_pandas_object/show_versions/test其余 API 不保证稳定。这也是 index.rst 对半公开模块的精确措辞——使用时请以文档清单为准。四、API Reference 文档的组织结构toctree 导航index.rst通过 Sphinxtoctree将 API 参考文档组织为 18 个章节这是检索 pandas API 的官方目录结构io → 输入输出 general_functions → 通用函数 series → Series frame → DataFrame arrays → 数组、标量、数据类型 indexing → 索引对象 offset_frequency → 偏移量与频率 window → 窗口函数 groupby → 分组聚合 resampling → 重采样 style → 样式 plotting → 绘图 options → 配置选项 extensions → 扩展 testing → 测试工具 missing_value → 缺失值 aliases → 别名该 toctree 与文档主页的入口存在联动文档构建时doc/source/index.rst.template 在include_api为真时把reference/index加入主目录树因此 API Reference 页会出现在 pandas 文档首页的导航中。index.rst中还有一条开发者约定修改该 toctree 时必须同步更新 index.rst.template 中的手动目录保证两处章节列表一致。五、从顶层命名空间看 API 分类结合 pandas/init.py 的导入结构顶层公共 API 可以归纳为以下几个功能族数据类型dtypeInt8Dtype~Int64Dtype、UInt8Dtype~UInt64Dtype、Float32Dtype/Float64Dtype、BooleanDtype、StringDtype、CategoricalDtype、PeriodDtype、IntervalDtype、DatetimeTZDtype、SparseDtype、ArrowDtype。缺失值NA、NaT、isna/isnull、notna/notnull。索引对象Index、RangeIndex、CategoricalIndex、MultiIndex、IntervalIndex、TimedeltaIndex、DatetimeIndex、PeriodIndex、IndexSlice。时间序列Timestamp、Timedelta、Period、DateOffset、date_range、bdate_range、period_range、timedelta_range、interval_range、infer_freq。类型转换to_numeric、to_datetime、to_timedelta。核心数据结构与创建DataFrame、Series、Index、Categorical、array、Flags、Grouper、NamedAgg。重塑与计算concat、merge、merge_asof、merge_ordered、pivot、pivot_table、crosstab、melt、wide_to_long、cut、qcut、get_dummies、from_dummies、factorize、unique、eval。I/Oread_csv、read_excel、read_json、read_parquet、read_hdf、read_sql、read_html、read_xml、read_stata、read_sas、read_spss、read_feather、read_orc、read_iceberg、read_pickle、read_fwf、read_table、read_clipboard以及写入侧to_pickle、ExcelFile、ExcelWriter、HDFStore。系统信息show_versions打印环境与依赖版本排查问题必备、test运行 pandas 自带测试。六、数组、标量与数据类型API 的类型地图doc/source/reference/arrays.rst 是理解 pandas 类型系统的一等文档。它开篇给出核心事实大多数数据类型下pandas 使用 NumPy 数组作为Index、Series、DataFrame内部的实际存储对象而对于部分数据类型pandas 扩展了 NumPy 的类型系统并为这些扩展类型提供字符串别名可在basics.dtypes中找到。下表是官方提供的完整映射关系数据类型pandas Data Type标量数组带时区 datetimeDatetimeTZDtypeTimestampDatetimeArray时间差无TimedeltaTimedeltaArray周期时间段PeriodDtypePeriodPeriodArray区间IntervalDtypeIntervalIntervalArray可空整数Int64Dtype等无IntegerArray可空浮点Float64Dtype等无FloatingArray分类CategoricalDtype无Categorical稀疏SparseDtype无SparseArray字符串StringDtypestrStringArray可空布尔BooleanDtypeboolBooleanArrayPyArrowArrowDtypePython 标量或NAArrowExtensionArray值得强调的几点设计细节可空整数/浮点/布尔numpy.ndarray无法原生表达带缺失值的整数数据缺失值无法用 NaN 表示这正是IntegerArray、FloatingArray、BooleanArray存在的理由——它们用掩码mask记录缺失位置从而在Int64、Float64、boolean等 dtype 下同时支持数值与NA。时区感知 datetimeNumPy 无法原生表示带时区的 datetimepandas 通过DatetimeArray扩展数组解决带时区数据的 dtype 是DatetimeTZDtype无时区数据则退化为np.dtype(datetime64[ns])。若数据带时区则数组中每个值的时区必须一致。分类数据CategoricalDtype描述有限取值集合Categorical.from_codes可在已有类别与整数编码时直接构造np.asarray(categorical)会丢失类别与有序性信息只保留底层数值。顶层array方法pd.array()可创建任意扩展数组结果可存入Series、Index或DataFrame列。类型内省工具pandas.api.types提供is_*_dtype系列函数如is_integer_dtype、is_datetime64_any_dtype、is_extension_array_dtype、infer_dtype、pandas_dtype、union_categoricals等构造与判断函数覆盖数据类型、可迭代对象、标量三类内省场景。PyArrow 类型对应关系arrays.rst还给出了 pandas 与 PyArrow 的类型对应表这是使用pd.ArrowDtype(...)时的直接参考。PyArrow 类型需要传入ArrowDtype才能被 pandas 识别例如pd.ArrowDtype(pa.bool_())PyArrow 类型pandas 扩展类型NumPy 类型pyarrow.bool_BooleanDtypenp.bool_pyarrow.int8~int64Int8Dtype~Int64Dtypenp.int8~np.int64pyarrow.uint8~uint64UInt8Dtype~UInt64Dtypenp.uint8~np.uint64pyarrow.float32/float64Float32Dtype/Float64Dtypenp.float32/np.float64pyarrow.timestampDatetimeTZDtypenp.datetime64pyarrow.duration无np.timedelta64pyarrow.stringStringDtypenp.str_pyarrow.dictionaryCategoricalDtype无pyarrow.time32/time64/date32/date64/binary/decimal128/list_/map_无无ArrowExtensionArray以pyarrow.ChunkedArray加pyarrow.DataType为底层存储而非 NumPy 数组其.dtype是ArrowDtype。官方明确标注该特性处于实验阶段API 可能在未来版本无预警变更。此外PyArrow 字符串支持可由pd.StringDtype(pyarrow)与pd.ArrowDtype(pa.string())两种途径提供前者对应字符串别名string[pyarrow]后者与其他ArrowDtype类型的互操作性通常更好。虽然内部以 PyArrow 对象存储但读取出的标量会被转换回对应 Python 标量如 int64 返回 Pythonint缺失值返回NA。七、如何高效使用 API Reference 文档按结构检索先确定对象属于哪一类Series / DataFrame / 通用函数 / 索引 / 窗口…再进入对应的章节页面如 doc/source/reference/series.rst、doc/source/reference/frame.rst、doc/source/reference/window.rst。每章都会以autosummary列表按属性 / 方法 / 构造器分类呈现例如Index章节就拆分为 Properties、Modifying and computations、Boolean comparisons、Set operations 等多个小节。区分直接用与看文档用对Index的方法官方提示许多方法或其变体在包含该索引的对象Series/DataFrame上也可用且通常应优先通过 Series/DataFrame 调用而非直接调用 Index 方法。善用别名与迁移文档doc/source/reference/aliases.rst 专门收录 API 别名配合 doc/source/reference/missing_value.rst缺失值与 doc/source/reference/options.rst配置项可覆盖日常高频场景。关注实验性标记文档中对实验性 API如 PyArrow 支持、pandas.api.interchange的部分能力会给出 warning/note使用前需评估 API 变动风险。八、结论pandas 的公共 API 由一套清晰的分层契约定义顶层pandas.*命名空间以__all__固化是核心稳定面pandas.errors、pandas.plotting、pandas.testing与pandas.api.*系列子包各司其职而pandas.core/pandas.compat则是明确不保证稳定的私有区。API Reference 的 18 个章节既是文档导航骨架也是理解 pandas 类型系统扩展 dtype、PyArrow 支持、缺失值语义与功能模块划分的最佳入口。无论是日常调用还是为 pandas 编写扩展以 doc/source/reference/index.rst 这张API 地图为准就能始终停留在受兼容性保护的公共面上。【免费下载链接】pandasFlexible and powerful data analysis / manipulation library for Python, providing labeled data structures similar to R data.frame objects, statistical functions, and much more项目地址: https://gitcode.com/gh_mirrors/pa/pandas创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门