如果指定为列表,为什么 IPython.display.display 会以不同的顺序呈现输出?
Why does IPython.display.display render outputs in different order if specified as a list?
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()
是结果中的第三项。然而,这首先呈现 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)
这是因为 df.info()
除了打印信息外没有 return 任何东西,解决方法是将信息信息保存为字符串,然后将它们保存在 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
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()
是结果中的第三项。然而,这首先呈现 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)
这是因为 df.info()
除了打印信息外没有 return 任何东西,解决方法是将信息信息保存为字符串,然后将它们保存在 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