python - 让 Pandas 找出在 pd.read_excel 中要跳过的行数
问题描述
我正在尝试将数百个 excel 文件自动读入单个数据框中。值得庆幸的是,excel 文件的布局相当稳定。它们都有相同的标题(标题的大小写可能会有所不同),当然还有相同的列数,我要读取的数据总是存储在第一个电子表格中。
但是,在某些文件中,在实际数据开始之前已经跳过了许多行。在实际数据之前的行中可能有也可能没有评论等。例如,在某些文件中,标题位于第 3 行,然后数据从第 4 行开始向下。
我想pandas
自己弄清楚要跳过多少行。目前我使用一个有点复杂的解决方案......我首先将文件读入数据帧,检查标题是否正确,如果没有搜索找到包含标题的行,然后重新读取文件现在知道要多少行跳过..
def find_header_row(df, my_header):
"""Find the row containing the header."""
for idx, row in df.iterrows():
row_header = [str(t).lower() for t in row]
if len(set(my_header) - set(row_header)) == 0:
return idx + 1
raise Exception("Cant find header row!")
my_header = ['col_1', 'col_2',..., 'col_n']
df = pd.read_excel('my_file.xlsx')
# Make columns lower case (case may vary)
df.columns = [t.lower() for t in df.columns]
# Check if the header of the dataframe mathces my_header
if len(set(my_header) - set(df.columns)) != 0:
# If no... use my function to find the row containing the header
n_rows_to_skip = find_header_row(df, kolonner)
# Re-read the dataframe, skipping the right number of rows
df = pd.read_excel(fil, skiprows=n_rows_to_skip)
既然我知道标题行的样子,有没有办法让pandas
自己弄清楚数据从哪里开始?或者有人能想到更好的解决方案吗?
解决方案
让我们知道这是否适合您
import pandas as pd
df = pd.read_excel("unamed1.xlsx")
df
Unnamed: 0 Unnamed: 1 Unnamed: 2
0 NaN bad row1 badddd row111 NaN
1 baaaa NaN NaN
2 NaN NaN NaN
3 id name age
4 1 Roger 17
5 2 Rosa 23
6 3 Rob 31
7 4 Ives 15
first_row = (df.count(axis = 1) >= df.shape[1]).idxmax()
df.columns = df.loc[first_row]
df = df.loc[first_row+1:]
df
3 id name age
4 1 Roger 17
5 2 Rosa 23
6 3 Rob 31
7 4 Ives 15
推荐阅读
- javascript - 如何使用正则表达式验证此类输入?
- transactions - 我的后端可以调用智能合约函数在某个日期执行吗?
- ansible - 我已经使用寄存器变量来存储任务的输出值,所以我在来自 ansible 角色的条件下使用相同的值
- vue.js - 异步加载 Vue 插件
- pandas - 当元组是字典的值时仅检索元组的一个元素
- progressive-web-apps - 将上传文件的路径存储在客户端或浏览器外部的文件以供离线使用
- java - 应用操作正在使用 AATP(应用操作测试工具),但不能从谷歌助手工作
- powershell - 运行 AZ 命令的 Azure Functions
- c# - 过滤器配置在不同的窗口 C# WPF
- java - 如何将来自多个 Access 行的数据插入到 Java 中的单个多行字符串中