pandas 文档字符串指南#
关于文档字符串和标准#
Python 文档字符串是用于记录 Python 模块、类、函数或方法的字符串,以便程序员无需阅读实现细节即可理解其功能。
此外,通常的做法是从文档字符串自动生成在线(html)文档。 Sphinx 用于此目的。
下一个示例可以说明文档字符串的外观
def add(num1, num2):
"""
Add up two integer numbers.
This function simply wraps the ``+`` operator, and does not
do anything interesting, except for illustrating what
the docstring of a very simple function looks like.
Parameters
----------
num1 : int
First number to add.
num2 : int
Second number to add.
Returns
-------
int
The sum of ``num1`` and ``num2``.
See Also
--------
subtract : Subtract one integer from another.
Examples
--------
>>> add(2, 2)
4
>>> add(25, 0)
25
>>> add(10, -10)
0
"""
return num1 + num2
存在一些关于文档字符串的标准,这使得它们更易于阅读,并且允许它们轻松导出为其他格式,如 html 或 pdf。
每个 Python 文档字符串都应遵循的第一个约定定义在 PEP-257 中。
由于 PEP-257 相当宽泛,因此还存在其他更具体的标准。对于 pandas,遵循 NumPy 文档字符串约定。这些约定在本文件中进行了说明。
numpydoc 是一个 Sphinx 扩展,用于支持 NumPy 文档字符串约定。
该标准使用 reStructuredText (reST)。reStructuredText 是一种标记语言,允许在纯文本文件中编码样式。有关 reStructuredText 的文档可以在以下位置找到:
pandas 提供了一些帮助程序,用于在相关类之间共享文档字符串,请参阅 共享文档字符串。
本文档的其余部分将总结以上所有指南,并提供 pandas 项目特有的其他约定。
编写文档字符串#
一般规则#
文档字符串必须用三个双引号定义。文档字符串之前或之后不应留有空行。文本从引号行之后开始。结束引号应单独占一行(意味着它们不与最后一句在同一行)。
极少数情况下,文档字符串中会使用 reST 样式,如粗体或斜体,但通常会包含行内代码,用反引号括起来。以下内容被视为行内代码:
参数的名称
Python 代码、模块、函数、内置函数、类型、字面量……(例如
os、list、numpy.abs、datetime.date、True)pandas 类(形式为
:class:`pandas.Series`)pandas 方法(形式为
:meth:`pandas.Series.sum`)pandas 函数(形式为
:func:`pandas.to_datetime`)
注意
要仅显示链接的类、方法或函数的最后一个组件,请在其前面加上 ~。例如,:class:`~pandas.Series` 将链接到 pandas.Series,但仅显示最后一部分 Series 作为链接文本。有关详细信息,请参阅 Sphinx 交叉引用语法。
好
def add_values(arr):
"""
Add the values in ``arr``.
This is equivalent to Python ``sum`` of :meth:`pandas.Series.sum`.
Some sections are omitted here for simplicity.
"""
return sum(arr)
坏
def func():
"""Some function.
With several mistakes in the docstring.
It has a blank line after the signature ``def func():``.
The text 'Some function' should go in the line after the
opening quotes of the docstring, not in the same line.
There is a blank line between the docstring and the first line
of code ``foo = 1``.
The closing quotes should be in the next line, not in this one."""
foo = 1
bar = 2
return foo + bar
第 1 部分:简短摘要#
简短摘要是简洁地描述函数功能的单一句子。
简短摘要必须以大写字母开头,以句号结尾,并占一行。它需要描述对象的用途,而不提供详细信息。对于函数和方法,简短摘要必须以不定式动词开头。
好
def astype(dtype):
"""
Cast Series type.
This section will provide further details.
"""
pass
坏
def astype(dtype):
"""
Casts Series type.
Verb in third-person of the present simple, should be infinitive.
"""
pass
def astype(dtype):
"""
Method to cast Series type.
Does not start with verb.
"""
pass
def astype(dtype):
"""
Cast Series type
Missing dot at the end.
"""
pass
def astype(dtype):
"""
Cast Series type from its current type to the new type defined in
the parameter dtype.
Summary is too verbose and doesn't fit in a single line.
"""
pass
第 2 部分:扩展摘要#
扩展摘要提供了函数功能的详细信息。它不应深入讨论参数的细节,或讨论实现说明,这些内容应放在其他部分。
在简短摘要和扩展摘要之间留有一个空行。扩展摘要中的每个段落都以句号结尾。
扩展摘要应提供函数有用性的原因及其用例,如果它们不是过于笼统的话。
def unstack():
"""
Pivot a row index to columns.
When using a MultiIndex, a level can be pivoted so each value in
the index becomes a column. This is especially useful when a subindex
is repeated for the main index, and data is easier to visualize as a
pivot table.
The index level will be automatically removed from the index when added
as columns.
"""
pass
第 3 部分:参数#
参数的详细信息将在此部分添加。此部分标题为“Parameters”,后面跟着一个与“Parameters”一词的每个字母对齐的连字符行。在节标题之前留有一个空行,但之后不留,在“Parameters”一词行和连字符行之间也不留。
标题之后,签名中的每个参数都必须进行文档记录,包括 *args 和 **kwargs,但不包括 self。
参数通过其名称定义,后跟一个空格、一个冒号、另一个空格和类型(或类型)。请注意,名称和冒号之间的空格很重要。对于 *args 和 **kwargs 没有定义类型,但所有其他参数都必须定义类型。参数定义之后,必须有一行缩进的参数描述,该描述可以有多行。描述必须以大写字母开头,并以句号结尾。
对于带有默认值的关键字参数,默认值将列在类型末尾的逗号之后。在这种情况下,类型的确切形式将是“int, default 0”。在某些情况下,解释默认参数的含义可能很有用,可以在逗号之后添加“int, default -1, meaning all cpus”。
当默认值为 None 时,表示该值不会被使用。而不是 "str, default None",首选写法是 "str, optional"。当 None 是一个被使用的值时,我们将保留“str, default None”的形式。例如,在 df.to_csv(compression=None) 中,None 不是一个被使用的值,而是表示压缩是可选的,如果不提供则不使用压缩。在这种情况下,我们将使用 "str, optional"。只有在 func(value=None) 且 None 被使用的值与 0 或 foo 的使用方式相同的情况下,我们才会指定“str, int or None, default None”。
好
class Series:
def plot(self, kind, color='blue', **kwargs):
"""
Generate a plot.
Render the data in the Series as a matplotlib plot of the
specified kind.
Parameters
----------
kind : str
Kind of matplotlib plot.
color : str, default 'blue'
Color name or rgb code.
**kwargs
These parameters will be passed to the matplotlib plotting
function.
"""
pass
坏
class Series:
def plot(self, kind, **kwargs):
"""
Generate a plot.
Render the data in the Series as a matplotlib plot of the
specified kind.
Note the blank line between the parameters title and the first
parameter. Also, note that after the name of the parameter ``kind``
and before the colon, a space is missing.
Also, note that the parameter descriptions do not start with a
capital letter, and do not finish with a dot.
Finally, the ``**kwargs`` parameter is missing.
Parameters
----------
kind: str
kind of matplotlib plot
"""
pass
参数类型#
指定参数类型时,可以直接使用 Python 内置数据类型(优先使用 Python 类型而不是更冗长的字符串、整数、布尔值等)。
int
float
str
bool
对于复杂类型,请定义子类型。对于 dict 和 tuple,由于存在多种类型,我们使用括号来方便阅读类型(字典使用花括号,元组使用圆括号)。
int 列表
str : int 的字典
(str, int, int) 的元组
(str,) 的元组
str 的集合
如果只允许一组值,则将它们放在花括号中并用逗号(后跟空格)分隔。如果这些值是序数且有顺序,请按此顺序排列。否则,先列出默认值(如果存在)。
{0, 10, 25}
{‘simple’, ‘advanced’}
{‘low’, ‘medium’, ‘high’}
{‘cat’, ‘dog’, ‘bird’}
如果类型定义在 Python 模块中,则必须指定模块。
datetime.date
datetime.datetime
decimal.Decimal
如果类型在包中,则还必须指定模块。
numpy.ndarray
scipy.sparse.coo_matrix
如果类型是 pandas 类型,除了 Series 和 DataFrame 外,还需指定 pandas。
Series
DataFrame
pandas.Index
pandas.Categorical
pandas.arrays.SparseArray
如果精确类型不重要,但必须与 NumPy 数组兼容,则可以指定 array-like。如果接受任何可迭代的类型,则可以使用 iterable。
array-like
iterable
如果接受多种类型,则用逗号分隔,最后一个类型前需要用“or”分隔。
int 或 float
float, decimal.Decimal 或 None
str 或 str 列表
如果 None 是可接受的值之一,它必须始终放在列表的最后。
对于轴,约定使用类似以下形式:
axis : {0 or ‘index’, 1 or ‘columns’, None}, default None
第 4 部分:返回或产生#
如果方法返回一个值,它将在本节中记录。方法产生输出时也同样记录。
本节的标题将以与“Parameters”相同的方式定义。名称为“Returns”或“Yields”,后面跟着一个与前面单词字母数相同的连字符行。
返回值的文档记录方式与参数类似。但在此情况下,除非方法返回或产生多个值(值元组),否则不会提供名称。
“Returns”和“Yields”的类型与“Parameters”的类型相同。此外,描述必须以句号结尾。
例如,对于单个值
def sample():
"""
Generate and return a random number.
The value is sampled from a continuous uniform distribution between
0 and 1.
Returns
-------
float
Random number generated.
"""
return np.random.random()
对于多个值
import string
def random_letters():
"""
Generate and return a sequence of random letters.
The length of the returned string is also random, and is also
returned.
Returns
-------
length : int
Length of the returned string.
letters : str
String of random letters.
"""
length = np.random.randint(1, 10)
letters = ''.join(np.random.choice(string.ascii_lowercase)
for i in range(length))
return length, letters
如果方法产生其值
def sample_values():
"""
Generate an infinite sequence of random numbers.
The values are sampled from a continuous uniform distribution between
0 and 1.
Yields
------
float
Random number generated.
"""
while True:
yield np.random.random()
第 5 部分:另请参阅#
本节用于告知用户与正在文档化的功能相关的 pandas 功能。极少数情况下,如果完全找不到相关的方法或函数,可以跳过此节。
一个明显的例子是 head() 和 tail() 方法。因为 tail() 执行的功能与 head() 相同,只是在 Series 或 DataFrame 的末尾而不是开头,所以最好让用户知道它。
为了直观地理解什么是相关的,这里有一些例子
loc和iloc,因为它们执行相同的功能,但在一个情况下提供索引,另一个情况下提供位置。max和min,因为它们执行相反的操作。iterrows、itertuples和items,因为用户寻找遍历列的方法时很容易找到遍历行的迭代器,反之亦然。fillna和dropna,因为这两种方法都用于处理缺失值。read_csv和to_csv,因为它们是互补的。merge和join,因为一个是一个的泛化。astype和pandas.to_datetime,因为用户可能正在阅读astype的文档以了解如何转换为日期,而这样做的方式是使用pandas.to_datetime。where与numpy.where相关,因为其功能基于后者。
在决定什么相关时,您应该主要运用常识,并考虑对于阅读文档的用户(尤其是经验较少的用户)来说什么是有用的。
当引用其他库(主要是 numpy)时,请先使用模块名称(而不是别名,如 np)。如果函数位于非主模块中,例如 scipy.sparse,请列出完整的模块(例如 scipy.sparse.coo_matrix)。
本节有一个标题“See Also”(注意 S 和 A 大写),后面跟着连字符行,前面有一个空行。
标题之后,我们将为每个相关的方法或函数添加一行,后跟一个空格、一个冒号、另一个空格,以及一个简短的描述,说明该方法或函数的作用、为何在此上下文中相关,以及被文档化的函数与被引用的函数之间的主要区别。描述也必须以句号结尾。
请注意,“Returns”和“Yields”中的描述位于类型后面的行上。而在此节中,描述位于同一行,中间用冒号分隔。如果描述无法在一行内显示,可以继续到下一行,该行必须进一步缩进。
例如:
class Series:
def head(self):
"""
Return the first 5 elements of the Series.
This function is mainly useful to preview the values of the
Series without displaying the whole of it.
Returns
-------
Series
Subset of the original series with the 5 first values.
See Also
--------
Series.tail : Return the last 5 elements of the Series.
Series.iloc : Return a slice of the elements in the Series,
which can also be used to return the first or last n.
"""
return self.iloc[:5]
第 6 部分:说明#
这是一个可选部分,用于说明算法实现方面的注意事项,或记录函数行为的技术方面。
您可以选择跳过此部分,除非您熟悉算法的实现,或者在为函数编写示例时发现了某些违反直觉的行为。
此部分遵循与扩展摘要部分相同的格式。
第 7 部分:示例#
这是文档字符串中最重要的部分之一,尽管它放在最后,因为人们通常通过示例比通过准确的解释更能理解概念。
文档字符串中的示例除了说明函数或方法的用法外,还必须是有效的 Python 代码,能够以确定的方式返回给定输出,并且用户可以复制并运行。
示例以 Python 终端会话的形式呈现。>>> 用于表示代码。... 用于表示上一行的代码延续。Sphinx 会在生成输出的代码行之后立即显示输出(之间没有空行)。描述示例的注释可以添加在它们之前和之后,并用空行分隔。
示例如下所示:
导入所需的库(除了
numpy和pandas)创建示例所需的数据
展示一个非常基本的示例,该示例可以说明最常见的用例
添加带有解释的示例,说明如何使用参数来实现扩展功能
一个简单的例子可以是
class Series:
def head(self, n=5):
"""
Return the first elements of the Series.
This function is mainly useful to preview the values of the
Series without displaying all of it.
Parameters
----------
n : int
Number of values to return.
Return
------
pandas.Series
Subset of the original series with the n first values.
See Also
--------
tail : Return the last n elements of the Series.
Examples
--------
>>> ser = pd.Series(['Ant', 'Bear', 'Cow', 'Dog', 'Falcon',
... 'Lion', 'Monkey', 'Rabbit', 'Zebra'])
>>> ser.head()
0 Ant
1 Bear
2 Cow
3 Dog
4 Falcon
dtype: object
With the ``n`` parameter, we can change the number of returned rows:
>>> ser.head(n=3)
0 Ant
1 Bear
2 Cow
dtype: object
"""
return self.iloc[:n]
示例应尽可能简洁。如果函数的复杂性需要较长的示例,建议使用带有粗体标题的块。使用双星号 ** 将文本设为粗体,例如 **this example**。
示例约定#
示例中的代码假定始终以这两行开头,这两行不显示
import numpy as np
import pandas as pd
示例中使用的任何其他模块都必须明确导入,每行一个(如 PEP 8#imports 所推荐),并避免使用别名。避免过多的导入,但如果需要,标准库的导入应放在前面,然后是第三方库(如 matplotlib)。
当用单个 Series 说明示例时,使用名称 ser,当用单个 DataFrame 说明示例时,使用名称 df。对于索引,idx 是首选名称。如果使用一组同类的 Series 或 DataFrame,则将它们命名为 ser1、ser2、ser3… 或 df1、df2、df3…。如果数据不同类,并且需要多个结构,则将它们命名为有意义的名称,例如 df_main 和 df_to_join。
示例中使用的数据应尽可能紧凑。建议行数为 4 行左右,但应使用对特定示例有意义的数量。例如,在 head 方法中,需要大于 5 行才能显示带有默认值的示例。如果计算 mean,我们可以使用类似 [1, 2, 3] 的值,这样很容易看到返回的值是平均值。
对于更复杂的示例(例如分组),避免使用无解释的数据,如列为 A、B、C、D… 的随机数矩阵。而是使用有意义的示例,这使得概念更容易理解。除非示例需要,否则使用动物名称,以保持示例的一致性。以及它们的数值属性。
调用方法时,首选关键字参数 head(n=3) 而非位置参数 head(3)。
好
class Series:
def mean(self):
"""
Compute the mean of the input.
Examples
--------
>>> ser = pd.Series([1, 2, 3])
>>> ser.mean()
2
"""
pass
def fillna(self, value):
"""
Replace missing values by ``value``.
Examples
--------
>>> ser = pd.Series([1, np.nan, 3])
>>> ser.fillna(0)
[1, 0, 3]
"""
pass
def groupby_mean(self):
"""
Group by index and return mean.
Examples
--------
>>> ser = pd.Series([380., 370., 24., 26],
... name='max_speed',
... index=['falcon', 'falcon', 'parrot', 'parrot'])
>>> ser.groupby_mean()
index
falcon 375.0
parrot 25.0
Name: max_speed, dtype: float64
"""
pass
def contains(self, pattern, case_sensitive=True, na=numpy.nan):
"""
Return whether each value contains ``pattern``.
In this case, we are illustrating how to use sections, even
if the example is simple enough and does not require them.
Examples
--------
>>> ser = pd.Series('Antelope', 'Lion', 'Zebra', np.nan)
>>> ser.contains(pattern='a')
0 False
1 False
2 True
3 NaN
dtype: bool
**Case sensitivity**
With ``case_sensitive`` set to ``False`` we can match ``a`` with both
``a`` and ``A``:
>>> s.contains(pattern='a', case_sensitive=False)
0 True
1 False
2 True
3 NaN
dtype: bool
**Missing values**
We can fill missing values in the output using the ``na`` parameter:
>>> ser.contains(pattern='a', na=False)
0 False
1 False
2 True
3 False
dtype: bool
"""
pass
坏
def method(foo=None, bar=None):
"""
A sample DataFrame method.
Do not import NumPy and pandas.
Try to use meaningful data, when it makes the example easier
to understand.
Try to avoid positional arguments like in ``df.method(1)``. They
can be all right if previously defined with a meaningful name,
like in ``present_value(interest_rate)``, but avoid them otherwise.
When presenting the behavior with different parameters, do not place
all the calls one next to the other. Instead, add a short sentence
explaining what the example shows.
Examples
--------
>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame(np.random.randn(3, 3),
... columns=('a', 'b', 'c'))
>>> df.method(1)
21
>>> df.method(bar=14)
123
"""
pass
让示例通过 doctests 的技巧#
让示例通过验证脚本中的 doctests 有时会很棘手。以下是一些注意事项:
导入所有必需的库(除了 pandas 和 NumPy,它们已作为
import pandas as pd和import numpy as np导入),并定义示例中使用的所有变量。尽量避免使用随机数据。然而,在某些情况下,随机数据可能是可以接受的,例如,如果您正在文档化的函数处理概率分布,或者使函数结果有意义所需的数据量过大,以至于手动创建非常麻烦。在这些情况下,请始终使用固定的随机种子,以使生成的示例可预测。示例:
>>> np.random.seed(42) >>> df = pd.DataFrame({'normal': np.random.normal(100, 5, 20)})
如果您有一个包装了多行的代码片段,您需要在继续的行上使用“…”
>>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], index=['a', 'b', 'c'], ... columns=['A', 'B'])
如果要显示引发异常的情况,可以这样做:
>>> pd.to_datetime(["712-01-01"]) Traceback (most recent call last): OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 712-01-01 00:00:00
包含“Traceback (most recent call last):”是必不可少的,但对于实际的错误,只需要错误名称就足够了。
如果结果中有很少一部分可能变化(例如,对象表示中的哈希),您可以使用
...来表示这部分。如果您想显示
s.plot()返回一个 matplotlib AxesSubplot 对象,这将导致 doctest 失败。>>> s.plot() <matplotlib.axes._subplots.AxesSubplot at 0x7efd0c0b0690>
但是,您可以这样做(请注意需要添加的注释):
>>> s.plot() <matplotlib.axes._subplots.AxesSubplot at ...>
示例中的绘图#
pandas 中有一些方法会返回绘图。为了在文档中渲染示例生成的绘图,存在 .. plot:: 指令。
要使用它,请在“Examples”标题之后放置以下代码,如下所示。在构建文档时,绘图将自动生成。
class Series:
def plot(self):
"""
Generate a plot with the ``Series`` data.
Examples
--------
.. plot::
:context: close-figs
>>> ser = pd.Series([1, 2, 3])
>>> ser.plot()
"""
pass