Pandas 提供了一组强大的 I/O 函数,可以轻松将不同格式的数据加载为 DataFrame。以下是三种最常用的读取方式:
| 文件格式 | Pandas 函数 | 常用参数示例 |
|---|---|---|
| 📄 CSV | pd.read_csv() | file.csv, encoding='utf-8', sep=',' |
| 📗 Excel | pd.read_excel() | file.xlsx, sheet_name='Sheet1' |
| 📋 JSON | pd.read_json() | file.json, orient='records' |
# 读取 CSV 文件 import pandas as pd df_csv = pd.read_csv('sales_data.csv', encoding='utf-8') # 读取 Excel 文件 (需安装 openpyxl) df_excel = pd.read_excel('inventory.xlsx', sheet_name='Sheet1') # 读取 JSON 文件 df_json = pd.read_json('users.json', orient='records')
💡 提示:读取时注意编码、分隔符、sheet 名称,必要时使用 nrows 参数预览部分数据。
加载数据后,立即使用以下四个方法快速了解数据全貌:
info() — 列类型、非空计数、内存占用describe() — 数值列统计摘要 (均值、分位数等)head(n) — 预览前 n 行 (默认5行)shape — 返回 (行数, 列数) 元组# 使用示例 (假设 df 是已读取的 DataFrame) print("===== 数据形状 =====") print(df.shape) # (1000, 12) print("\n===== 前5行 =====") print(df.head()) print("\n===== 基本信息 =====") df.info() print("\n===== 统计描述 =====") print(df.describe())
✔️ info() 帮你发现缺失值;describe() 识别异常数值;head() 直观感受字段内容;shape 确认数据量。
以下代码展示完整流程:读取 CSV 文件,并依次输出探索信息。
# 完整流程
import pandas as pd
df = pd.read_csv('student_scores.csv')
print('Shape:', df.shape)
print(df.head(3))
df.info()
print(df.describe())
⬆️ 数据从源文件经 Pandas 加载为 DataFrame,再调用探索方法
| 函数 | 参数 | 说明 | 示例 |
|---|---|---|---|
read_csv | sep | 分隔符 (默认逗号) | sep=';' |
encoding | 文件编码 | encoding='gbk' | |
nrows | 读取前 n 行 | nrows=100 | |
read_excel | sheet_name | 工作表名称或索引 | sheet_name=0 |
dtype | 指定列类型 | dtype={'id': str} | |
read_json | orient | JSON 结构格式 | orient='records' |
💡 使用 dtype 可加速读取并避免类型推断错误。
根据以下输出,判断数据框的基本信息:
# 某数据框输出
(800, 15)
RangeIndex: 800 entries, 0 to 799
Data columns (total 15 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 id 800 non-null int64
1 name 800 non-null object
2 age 780 non-null float64
3 salary 790 non-null float64
...
✅ 该数据框有 800 行、15 列;age 列存在 20 个缺失值;salary 列存在 10 个缺失值。使用 df.isnull().sum() 可进一步确认。