import pandas as pd
# 先将文件读到内存中形成一个datefream
people = pd.read_excel(r'People.xlsx')
# 查看行数和列数
print(people.shape)
# 查看列名
# 当直接打印datefream时 ID不会显示(datefream对待index和columns是分开对待的)
print(people.columns)
# 打印表中的前三行 默认为五行
print(people.head(3))
print('=========================')
# 查看末尾三行 默认为五行
print(people.tail(3))
# # pandas读取excel默认从第0行开始读取数据 设置head=1 默认为0
# # 但表格文件第一行为空时 会自动跳过(header不脏的时候)
# people = pd.read_excel(r'People.xlsx', header=1)
# 当不设置header时 会自动生成int类型的header
# 设置herder
people.columns = ('ID', 'Type', 'Title', 'FirstName', 'MiddleName', 'LastName')
# 不使用自动添加的索引列 使用ID列作为索引列
people.set_index('ID',inplace=True)
# 将设置好的数据存放到下面表格(output.xlsx)中
people.to_excel(r'output.xlsx')
print("It's OK ")
# 将自动打印的index去掉
# yi
people.set_index('ID')
# er
# 当 inplace=True 时 直接修改当前的datefream 不会再新添加index
people.set_index('ID',inplace=True)
# df = pd.read_excel(r'output.xlsx')
# # 当再次读取output时 发现id列又变成了普通列而不是index列 自动生成index
# print(df.head())
# 解决自动生成index列的方法(在读取数据的时候设置index为ID)
df = pd.read_excel(r'output.xlsx', index_col='ID')
df.to_excel(r'output2.xlsx')
print('Done')
people.xlsx:
output.xlsx:
output2.xlsx: