我正在尝试用Python运行以下代码。我期望的是,代码将读取Excel文件,删除第1行和第2行,然后将前几行数据打印到控制台:
import pandas as pd
path = 'C:\\Temp\\'
filename = 'datafile1.xlsx'
df = pd.read_excel(path + filename, sheet_name=1)
df = df.drop([0,1]) #delete the first two rows
print(df.head()) 我似乎不能在这里上传excel文件,所以我在这里截图: Excel文件
以下是控制台中显示的结果:
runfile('C:/Temp/getdata.py', wdir='C:/Temp')
Title Here Unnamed: 1 Unnamed: 2 Unnamed: 3 Unnamed: 4 Unnamed: 5
NaN NaN NaN NaN NaN NaN NaN
sort order Type reference cliref couref haref contref
2 FMN NaN b 5 dfs dfs-5
3 ACB NaN c 6 dfs dfs-6
3 ACB NaN d 7 fasf fasf-7前两行仍然存在:"Sort Order“应该首先出现,"Title Here”根本不应该显示。
我需要改变什么?提前感谢您的帮助。1:https://i.stack.imgur.com/nHdDh.png
发布于 2021-09-25 08:26:07
跳过2行尝试使用skiprows:
df = pd.read_excel(path + filename, sheet_name=1, skiprows=2) 发布于 2021-09-25 07:38:23
也许,如果我正确地理解了OP,因为问题不清楚,您不能删除它们,因为它们是作为头文件读取的。尝试读取没有标题的excel文件,如下所示:
df = pd.read_excel(path + filename, sheet_name=1, header=None)然后删除行
发布于 2021-09-25 09:01:31
尝试使用标题和索引列
对于excel文件

它可能看起来像这样
import pandas as pd
df = pd.read_excel("file.xlsx", header = [0,1],index_col=[0], skiprows = [1])它产生输出
Title here
type reference cliref couref haref contref
1 fun NaN a 4 fds fds-4
2 fmn NaN b 5 dfs dfs-5
3 acb NaN c 6 dfs dfs-6
3 acb NaN d 7 fasf fasf-7
5 dis NaN e 8 dfd dfd-8
4 exb NaN f 9 fds fds-9
4 exb NaN g 10 adf adf-10
4 exb NaN h 11 asdf asdf-11
4 exb NaN i 12 df df-12https://stackoverflow.com/questions/69323929
复制相似问题