
import pandas as pd
# 文件路径
filePath = r'C:\Users\Administrator\Desktop\Temp\1.xlsx'
# 1.读取 excel(默认第 1 行为标题,行索引为 0,即:header=0)
student = pd.read_excel(filePath)
print(student.columns)
# Index(['ID', 'Name', 'Age', 'Grade'], dtype='object')
场景2:指定第 n 行为标题

import pandas as pd
# 文件路径
filePath = r'C:\Users\Administrator\Desktop\Temp\1.xlsx'
# 场景2:excel 中第 2 行才是我们想要的标题(即:header=1)
student = pd.read_excel(filePath, header=1)
print(student.columns)
# Index(['ID', 'Name', 'Age', 'Grade'], dtype='object')
场景3:没有标题,需要人为给定

import pandas as pd
# 文件路径
filePath = r'C:\Users\Administrator\Desktop\Temp\1.xlsx'
# 场景3:excel 中没有标题,需要人为设定
student = pd.read_excel(filePath, header=None)
student.columns = ['ID', 'Name', 'Age', 'Grade']
student.set_index('ID', inplace=True) # 指定索引列,并替换原数据
student.to_excel(filePath) # 写入至 Excel
print(student)
# Name Age Grade
# ID
# 1 张三 18 90

这篇博客详细介绍了如何使用pandas在Python中操作Excel文件,包括设置index_col为索引列,指定dtype数据类型,skiprows跳过不需要的行,usercols选择列数,以及head和tail快速读取部分数据。同时,文章还涵盖了读写数据时的at()方法获取单元格,loc[]用于数据筛选,sort_values()进行数据排序等实用技巧,并提供了实战遍历Excel文件的场景。
最低0.47元/天 解锁文章
1034

被折叠的 条评论
为什么被折叠?



