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)
答案 0 :(得分: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