【问题标题】:Why does IPython.display.display render outputs in different order if specified as a list?如果指定为列表,为什么 IPython.display.display 会以不同的顺序呈现输出?
【发布时间】:2020-03-27 14:34:40
【问题描述】:
def inspect_df(df):
    results = (df.head(), df.tail(), df.info(), df.describe(include='all'),)
    for result in results:
        display(result)

df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})

inspect_df(df)

请注意,df.info() 是结果中的第三项。然而,这首先呈现信息的输出,然后是其余的项目。如何让它以指定的顺序打印输出?

但是,如果我显式调用显示(没有列表),它会正确呈现:

def inspect_df(df):
    display(df.head())
    display(df.tail())
    display(df.info())
    display(df.describe(include='all'))

df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})

inspect_df(df)

【问题讨论】:

    标签: pandas ipython jupyter


    【解决方案1】:

    这是因为df.info() 除了打印信息外不返回任何内容,解决方法是将信息信息保存为字符串,然后将它们保存在results 中以进行迭代;

    import io
    buffer = io.StringIO()
    df.info(buf=buffer)
    info_string = buffer.getvalue()
    
    def inspect_df(df):
        results = (df.head(), df.tail(), info_string , df.describe(include='all'),)
        for result in results:
            print(result)
    
    df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
    
    inspect_df(df)
    

       x  y
    0  1  4
    1  2  5
    2  3  6
       x  y
    0  1  4
    1  2  5
    2  3  6
    <class 'pandas.core.frame.DataFrame'>
    RangeIndex: 3 entries, 0 to 2
    Data columns (total 2 columns):
    x    3 non-null int64
    y    3 non-null int64
    dtypes: int64(2)
    memory usage: 176.0 bytes
    
             x    y
    count  3.0  3.0
    mean   2.0  5.0
    std    1.0  1.0
    min    1.0  4.0
    25%    1.5  4.5
    50%    2.0  5.0
    75%    2.5  5.5
    max    3.0  6.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      • 2020-09-12
      • 1970-01-01
      • 2014-01-07
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      相关资源
      最近更新 更多