进货篇-Day5|识菜明鉴:查看数据概览:head /tail/info /describe

0 次阅读 2026-10-21 14:32

📖 知识点

1. head () /tail ():看头看尾

数据很大时不能全打印,只看前几行或后几行:

df.head()     # 默认看前5行
df.head(10)   # 看前10行
df.tail()     # 默认看后5行
df.tail(3)    # 看最后3行

像翻台账,先翻开头几页、再翻结尾几页,就能大致知道记了些什么。

2. info ():看整体结构

df.info() 查看数据的 "档案"—— 行列数、列名、每列类型、非空数量:

df.info()

运行输出:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   菜名     4 non-null      object
 1   价格     4 non-null      int64
 2   数量     4 non-null      int64
dtypes: int64(2), object(1)

重点看:多少行、多少列、每列类型(object 文本 /int 数字)、有无缺失(non-null 数量)。

3. describe ():看数值统计

df.describe() 对数值列做统计汇总:计数、均值、标准差、最小 / 最大值、四分位数:

df.describe()

运行输出:

          价格        数量
count  4.000000   4.000000
mean   3.500000  18.750000
std    1.290994   8.539125
min    2.000000  10.000000
25%    2.750000  13.750000
50%    3.500000  17.500000
75%    4.250000  22.500000
max    5.000000  30.000000

快速看出数据的 "味道":均值、波动、极值一目了然。

💡 四招总结

方法作用
df.head(n)看前 n 行
df.tail(n)看后 n 行
df.info()看结构(行列、类型、缺失)
df.describe()看数值统计(均值、极值等)

⚠️ 易错提醒

  1. describe() 只统计数值列,文本列不参与
  2. info() 里的 object 表示文本 / 字符串列
  3. 数据量大时别直接 print(df) 全打,用 head/tail 最稳妥

⚔️ Kata 实战任务

任务需求:

  1. 导入 pandas,创建一个含数值和文本的 "食材"DataFrame(菜名、价格、数量)
  2. 用 head() 看前 2 行,tail(2) 看后 2 行
  3. 用 info() 查看表格结构
  4. 用 describe() 查看数值列的统计汇总
  5. 对比四招各自的观察角度

参考代码

import pandas as pd

# 进货一批食材
data = {
    "菜名": ["白菜", "番茄", "土豆", "黄瓜", "茄子", "冬瓜"],
    "价格": [3, 5, 2, 4, 6, 1],
    "数量": [10, 20, 30, 15, 25, 40],
}
df = pd.DataFrame(data)

# 识菜明鉴四招
print("===== head:看前2行 =====")
print(df.head(2))

print("\n===== tail:看后2行 =====")
print(df.tail(2))

print("\n===== info:看结构 =====")
df.info()

print("\n===== describe:看数值统计 =====")
print(df.describe())

运行输出:

===== head:看前2行 =====
   菜名  价格  数量
0  白菜    3   10
1  番茄    5   20

===== tail:看后2行 =====
   菜名  价格  数量
4  茄子    6   25
5  冬瓜    1   40

===== info:看结构 =====
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6 entries, 0 to 5
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   菜名     6 non-null      object
 1   价格     6 non-null      int64
 2   数量     6 non-null      int64
dtypes: int64(2), object(1)

===== describe:看数值统计 =====
          价格        数量
count  6.000000   6.000000
mean   3.500000  23.333333
std    1.870829  11.690452
min    1.000000  10.000000
25%    2.250000  16.250000
50%    3.500000  22.500000
75%    4.750000  28.750000
max    6.000000  40.000000

🧠 思考题

  1. 数据有 1000 行,想看数据 "大概长什么样",应该用哪个方法?直接 print (df) 有什么问题?
  2. describe() 为什么只统计数值列?如果想看文本列的情况,该用什么方法?