- 将DataFrame数据写入excel文件。
- 没有限制时,会自动添加index。
- 用字典创建时的key则自动为column。
- 如果想去掉自动生成的index,可以用set_index指定,但不会改变原df。如果想要改变,使用inplace参数。
import pandas as pd
file = r"D:\xlsx\test1.xlsx"
df1 = pd.DataFrame({"ID": ["a", "b", "c"], "name": ["Lucy", "Jim", "Lily"], "score": [70, 80, 90]})
print(df1)
df1.to_excel(file)
ID name score
0 a Lucy 70
1 b Jim 80
2 c Lily 90
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ialhr6fy-1661600614670)(attachment:image.png)]
df1 = df1.set_index("ID")
print(df1)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RaHVqYbh-1661600614673)(attachment:image.png)]
df1 = pd.DataFrame({"ID": ["a", "b", "c"], "name": ["Lucy", "Jim", "Lily"], "score": [70, 80, 90]})
df1.set_index("ID", inplace=True)
print(df1)
- 当从excel读取文件时,也会自动在生成的数据上加index。
import pandas as pd
file_src = r"D:\xlsx\test1.xlsx"
file_dst = r"D:\xlsx\test2.xlsx"
df1 = pd.read_excel(file_src)
print(df1)
ID name score
0 a Lucy 70
1 b Jim 80
2 c Lily 90
查看行列及前后几行
df1.head(2)
IDnamescore0aLucy701bJim80
df1.tail(2)
IDnamescore1bJim802cLily90
df1.shape
(3, 3)
数据header不是excel的第一行
- 使用header指定第几行,注意excel的第一行对应的header为0
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BttICNzc-1661600614674)(attachment:image.png)]
df1 = pd.read_excel(file_src,header=1)
df1.columns
Index(['ID', 'name', 'score'], dtype='object')
数据无header
- 在读取时header指定为None,使用columns指定header
- 在读取时,使用names指定
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-H4CSL6m2-1661600614675)(attachment:image.png)]
df1 = pd.read_excel(file_src, header=None)
df1.columns = ["ID", "name", "score"]
df1.columns
Index(['ID', 'name', 'score'], dtype='object')
df1 = pd.read_excel(file_src, names=["ID", "name", "score"])
df1.columns
Index(['ID', 'name', 'score'], dtype='object')
读入数据时将index删除掉
- 使用index_col参数设置读入时的index
file_src = r"D:\xlsx\test2.xlsx"
df1 = pd.read_excel(file_src)
df1
IDnamescore0aLucy701bJim802cLily90
file_src = r"D:\xlsx\test2.xlsx"
file_dst = r"D:\xlsx\test3.xlsx"
df1 = pd.read_excel(file_src, index_col="ID")
print(df1)
df1.to_excel(file_dst)
读取指定的列
- 使用usecols指定,可以为数字或者字母,列表或者切片。
指定读取的行数
- nrows=数字
file_src = r"D:\xlsx\test2.xlsx"
df1 = pd.read_excel(file_src, nrows=2, index_col="ID")
print(df1)
name score
ID
a Lucy 70
b Jim 80
指定跳过的行
- skiprows=列表
file_src = r"D:\xlsx\test2.xlsx"
df1 = pd.read_excel(file_src, skiprows=[1,3], index_col="ID")
print(df1)
name score
ID
b Jim 80
详细可参考 https://editor.csdn.net/md/?articleId=126057819
Original: https://blog.csdn.net/weixin_48668114/article/details/126561674
Author: weixin_48668114
Title: pandas创建及读取excel文件
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/741508/
转载文章受原作者版权保护。转载请注明原作者出处!