当索引具有名称时,Pandas doctest不起作用

问题描述 投票:0回答:1

我正在尝试编写doctest,但是执行它们时出现一些错误。当我编写一个用pandas.DataFrame检索index.name的doctest时,测试失败。

MRE:

注意:

  • pandas_doctest_with_indexname(无效)
  • pandas_doctest(工作)
import pandas as pd


def pandas_doctest_with_indexname():
    """Function with pandas doctest.

    Returns
    -------
    pandas.DataFrame

    Example
    -------
    >>> df = pandas_doctest_with_indexname()
    >>> df.head()
       a  b
    x
    0  1  2
    1  3  4
    """

    df = pd.DataFrame([[1,2], [3,4]], columns=["a", "b"])
    df.index.name = "x"
    return df


def pandas_doctest():
    """Function with pandas doctest.

    Returns
    -------
    pandas.DataFrame

    Example
    -------
    >>> df = pandas_doctest()
    >>> df.head()
       a  b
    0  1  2
    1  3  4

    """

    df = pd.DataFrame([[1,2], [3,4]], columns=["a", "b"])
    return df


if __name__ == "__main__":
    import doctest
    doctest.testmod()

错误:

:!python pandas_doctst_mre.py
**********************************************************************
File "pandas_doctst_mre.py", line 13, in __main__.pandas_doctest_with_indexname
Failed example:
    df.head()
Expected:
       a  b
    x
    0  1  2
    1  3  4
Got:
       a  b
    x
    0  1  2
    1  3  4
**********************************************************************
1 items had failures:
   1 of   2 in __main__.pandas_doctest_with_indexname
***Test Failed*** 1 failures.


python-3.x pandas doctest
1个回答
0
投票

主要问题是索引名称x旁边缺少空格。由于某种原因,doctest捕获的输出将在右边的空白处填充空格,以使所有行具有相同的宽度。

因此,我在x行中填充了空格以使其与b对齐,现在它可以工作。

def pandas_doctest_with_indexname():
    """Function with pandas doctest.

    Returns
    -------
    pandas.DataFrame

    Example
    -------
    >>> df = pandas_doctest_with_indexname()
    >>> df.head()
       a  b
    x      
    0  1  2
    1  3  4
    """

    df = pd.DataFrame([[1,2], [3,4]], columns=["a", "b"])
    df.index.name = "x"
    return df

if __name__ == "__main__":
    import doctest
    doctest.testmod()
© www.soinside.com 2019 - 2024. All rights reserved.