电子表格简介

使用 pandas 高效导入数据

Amany Mahfouz

Instructor

电子表格

  • 也称为 Excel 文件
  • 数据以表格形式存储,单元格按行和列排列
  • 与平面文件不同,可包含格式和公式
  • 一个工作簿可包含多个工作表
使用 pandas 高效导入数据

加载电子表格

  • pandas 中,电子表格有专用读取函数:read_excel()

电子表格程序中的 FreeCodeCamp 新开发者调查数据截图

使用 pandas 高效导入数据

加载电子表格

import pandas as pd

# 读取 Excel 文件
survey_data = pd.read_excel("fcc_survey.xlsx")

# 查看前 5 行 print(survey_data.head())
    Age  AttendedBootcamp       ...                    SchoolMajor  StudentDebtOwe
0  28.0               0.0       ...                            NaN           20000
1  22.0               0.0       ...                            NaN             NaN
2  19.0               0.0       ...                            NaN             NaN
3  26.0               0.0       ...        Cinematography And Film            7000
4  20.0               0.0       ...                            NaN             NaN

[5 rows x 98 columns]
使用 pandas 高效导入数据

选择性加载列与行

带有元数据表头行的调查数据表格

包含多个小表的数据发票表格

使用 pandas 高效导入数据

选择性加载列与行

  • read_excel()read_csv() 共享许多关键字参数
    • nrows:限制读取的行数
    • skiprows:指定要跳过的行数或行号
    • usecols:按名称、位置编号或字母选择列(如 "A:P")
使用 pandas 高效导入数据

选择性加载列与行

使用 pandas 高效导入数据

选择性加载列与行

# 读取文件的 W-AB 和 AR 列,跳过元数据表头
survey_data = pd.read_excel("fcc_survey_with_headers.xlsx",
                            skiprows=2,
                            usecols="W:AB, AR")

# 查看数据 print(survey_data.head())
   CommuteTime            CountryCitizen  ...    EmploymentFieldOther    EmploymentStatus   Income
0         35.0  United States of America  ...                     NaN  Employed for wages  32000.0
1         90.0  United States of America  ...                     NaN  Employed for wages  15000.0
2         45.0  United States of America  ...                     NaN  Employed for wages  48000.0
3         45.0  United States of America  ...                     NaN  Employed for wages  43000.0
4         10.0  United States of America  ...                     NaN  Employed for wages   6000.0

[5 rows x 7 columns]
使用 pandas 高效导入数据

让我们练习吧!

使用 pandas 高效导入数据

Preparing Video For Download...