pandas docstring 指南#
关于 docstrings 和标准#
Python docstring 是一个用于记录 Python 模块、类、函数或方法的字符串,以便程序员无需阅读实现细节即可理解其功能。
此外,一种常见的做法是自动从 docstrings 生成在线(html)文档。Sphinx 就是为此目的服务的。
下一个示例可以说明 docstring 的样子:
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
存在一些关于 docstrings 的标准,这使得它们更易于阅读,并允许它们能够轻松地导出到其他格式,如 html 或 pdf。
每个 Python docstring 都应遵循的第一个约定定义在 PEP-257 中。
由于 PEP-257 相当宽泛,因此还存在其他更具体的标准。对于 pandas,遵循 NumPy docstring 约定。这些约定在此文档中进行了解释:
numpydoc 是一个 Sphinx 扩展,用于支持 NumPy docstring 约定。
该标准使用 reStructuredText (reST)。reStructuredText 是一种标记语言,允许在纯文本文件中编码样式。有关 reStructuredText 的文档可以在以下位置找到:
pandas 有一些用于在相关类之间共享 docstrings 的辅助工具,请参阅 共享文档字符串 。
本文档的其余部分将总结上述所有指南,并提供 pandas 项目特有的其他约定。
编写 docstring#
通用规则#
Docstrings 必须用三个双引号定义。在 docstring 之前或之后不应留有空行。文本从开引号的下一行开始。闭引号有自己的单独一行(这意味着它们不与最后一句在同一行)。
在极少数情况下,reST 样式(如粗体或斜体)会在 docstrings 中使用,但很少使用反引号括起来的内联代码。以下内容被视为内联代码:
参数的名称
Python 代码、模块、函数、内置函数、类型、字面量…(例如
os,list,numpy.abs,datetime.date,True)Pandas 类(形式为 ``
pandas.Series``)Pandas 方法(形式为 ``
pandas.Series.sum()``)Pandas 函数(形式为 ``
pandas.to_datetime()``)
备注
要只显示链接的类、方法或函数的最后一个组件,请在前面加上 ~。例如,:class:`~pandas.Series` `` 会链接到 ``pandas.Series,但只显示最后一个部分 Series 作为链接文本。有关详细信息,请参阅 Sphinx cross-referencing syntax 。
好的:
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 like 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,由于存在多个类型,我们使用括号来方便阅读类型(字典使用花括号 ``{}`,元组使用圆括号 ``()`):
list of int
dict of {str : int}
元组 (str, int, int)
元组 (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 类型,也请指定 pandas,但 Series 和 DataFrame 除外:
Series
DataFrame
pandas.Index
pandas.Categorical
pandas.arrays.SparseArray
如果确切的类型不重要,但必须与 NumPy 数组兼容,则可以指定 array-like。如果接受任何可迭代的类型,则可以使用 iterable:
array-like
iterable
如果接受多种类型,请用逗号分隔,最后两种类型之间用“or”分隔:
int or float
float, decimal.Decimal or None
str or list of str
如果 None 是可接受值之一,则它必须总是在列表的最后。
对于轴,约定使用如下格式:
axis : {0 or ‘index’, 1 or ‘columns’, None}, default None
第 4 部分:returns 或 yields#
如果方法返回值,将在本节中记录。如果方法产生输出,也会记录。
该部分的标题将与“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 部分:see also#
本节用于告知用户有关与正在记录的功能相关的 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_datetimewhere与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]
Section 6: notes#
这是一个可选部分,用于对算法实现进行注释,或记录函数行为的技术方面。
如果熟悉算法实现,或者在为函数编写示例时发现了一些反直觉的行为,可以随意跳过它。
这部分遵循与:“扩展摘要”部分相同的格式。
Section 7: examples#
这是文档字符串中最重要的一部分之一,尽管它位于最后,因为人们通常通过示例比通过准确的解释更能理解概念。
文档字符串中的示例除了说明函数或方法的用法外,还必须是有效的 Python 代码,能够以确定性的方式返回给定的输出,并且用户可以复制和运行。
示例以 Python 终端会话的形式呈现。 >>> 用于表示代码。 ... 用于表示来自上一行的继续行。输出显示在生成输出的最后一行代码之后(之间没有空行)。描述示例的注释可以在它们之前和之后添加空行。
呈现示例的方式如下:
导入所需的库(除了
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