类型注释熊猫数据框

时间:2019-07-26 19:17:34

标签: python pandas

您遇到的问题Pythonistas-如果函数或方法返回Pandas DataFrame,如何记录列名和列类型。有没有办法在Python的内置类型注释中做到这一点,还是只使用docstrings?而且,如果您仅使用文档字符串,那么如何格式化它们以使其尽可能简洁?我尝试的一切都没有什么Python风格。谢谢!

3 个答案:

答案 0 :(得分:2)

我在合理的情况下针对文档字符串中的数据帧执行此操作。有时这是不合理的。

:param dataframe: pd.DataFrame [M x (3+N)]
    'id': int
        ID column
    'value': int
        Number of things
    'color': str
        Color of things
    Remaining columns are properties; all should be float64s

也许有更好的方法可以做到这一点,但我还没有找到。

答案 1 :(得分:1)

文档字符串格式

我使用numpy docstring约定作为基础。如果函数的输入参数或返回参数是具有预定列的pandas数据框,则将带有列描述的reStructuredText样式table添加到参数描述中。例如:

def random_dataframe(no_rows):
    """Return dataframe with random data.

    Parameters
    ----------
    no_rows : int
        Desired number of data rows.

    Returns
    -------
    pd.DataFrame
        Dataframe with with randomly selected values. Data columns are as follows:

        ==========  ==============================================================
        rand_int    randomly chosen whole numbers (as `int`)
        rand_float  randomly chosen numbers with decimal parts (as `float`)
        rand_color  randomly chosen colors (as `str`)
        rand_bird   randomly chosen birds (as `str`)
        ==========  ==============================================================

    """
    df = pd.DataFrame({
        "rand_int": np.random.randint(0, 100, no_rows),
        "rand_float": np.random.rand(no_rows),
        "rand_color": np.random.choice(['green', 'red', 'blue', 'yellow'], no_rows),
        "rand_bird": np.random.choice(['kiwi', 'duck', 'owl', 'parrot'], no_rows),
    })

    return df

奖金:狮身人面像兼容性

上述docstring格式与sphinx autodoc文档生成器兼容。这是由sphinx自动生成的HTML文档中的文档字符串的样子(使用nature主题):

sphinx docstring

答案 2 :(得分:1)

我尝试过@Xukrao 的方法。有汇总表真是太好了。

同样受到another question in stackoverflow的启发,使用Number : 3 <class 'int'> Number : 3.14 <class 'float'> 块在修改方面更加方便。不必担心对齐和“=”。例如:

csv-table