如何使用Pandas跳过未知数量的行?

2024-06-28 20:52:49 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的示例中,我只能看到第一行数据的df.columns。但是,我想为不同的文件使用代码。对于其中一些,前几行是空的。我不知道确切的行数,因此无法使用f.e:skiprows=4。如何找到应跳过的空行数

path = r'D:\columntest.xlsx'
xlsx = pd.ExcelFile(path)
df = pd.read_excel(xlsx, sheet_name=0)

print(df.columns)

Tags: columns文件数据path代码示例dfread
2条回答

此解决方案的思想是将excel工作表加载到数据框中。然后将其存储到csv文件中。最后,我们打开csv文件并删除带有双分号的所有行

import pandas as pd

# load excel file
path_load = 'D:/columntest.xlsx'
xlsx = pd.ExcelFile(path)
df = pd.read_excel(path, sheet_name=0, header=None)

# store sheet as csv file
path_store = path_load[:-5] + '.csv'
df.to_csv(path_store, sep=';', index=False, header=False)

# process csv to remove lines with `;;`
with open(path_store, "r") as f:
    lines = f.readlines()
with open(path_store, "w") as f:
    for line in lines:
        if line.strip("\n") != ';;':
            f.write(line)

df = pd.read_csv(path_store, sep=';')

您可以使用drop_na方法:

df.dropna(how='all', inplace=True)
df = df.reset_index(drop=True)
df.columns = df.iloc[0]
df = df.drop(0)

相关问题 更多 >