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") #注意原df1不改变
print(df1)
name score
ID
a Lucy 70
b Jim 80
c Lily 90
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(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) #注意原df1改变
print(df1)
name score
ID
a Lucy 70
b Jim 80
c Lily 90
import pandas as pd
file_src = r"D:\xlsx\test1.xlsx"
file_dst = r"D:\xlsx\test2.xlsx"
df1 = pd.read_excel(file_src) #默认读出的数据会自动添加index, 会将首行数据作为column
print(df1)
ID name score
0 a Lucy 70
1 b Jim 80
2 c Lily 90
df1.head(2)
ID | name | score | |
---|---|---|---|
0 | a | Lucy | 70 |
1 | b | Jim | 80 |
df1.tail(2)
ID | name | score | |
---|---|---|---|
1 | b | Jim | 80 |
2 | c | Lily | 90 |
df1.shape
(3, 3)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BttICNzc-1661600614674)(attachment:image.png)]
df1 = pd.read_excel(file_src,header=1)
df1.columns
Index(['ID', 'name', 'score'], dtype='object')
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-H4CSL6m2-1661600614675)(attachment:image.png)]
# 使用header和columns配合
df1 = pd.read_excel(file_src, header=None)
df1.columns = ["ID", "name", "score"]
df1.columns
Index(['ID', 'name', 'score'], dtype='object')
# 使用names指定
df1 = pd.read_excel(file_src, names=["ID", "name", "score"])
df1.columns
Index(['ID', 'name', 'score'], dtype='object')
file_src = r"D:\xlsx\test2.xlsx"
df1 = pd.read_excel(file_src)
df1
ID | name | score | |
---|---|---|---|
0 | a | Lucy | 70 |
1 | b | Jim | 80 |
2 | c | Lily | 90 |
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)
name score
ID
a Lucy 70
b Jim 80
c Lily 90
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
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