简体   繁体   English

Pandas:从具有特定值的行下方开始读取 Excel 文件

[英]Pandas: reading Excel file starting from the row below that with a specific value

Say I have the following Excel file:假设我有以下 Excel 文件:

    A      B     C
0   -      -     -
1   Start  -     -
2   3      2     4
3   7      8     4
4   11     2     17

I want to read the file in a dataframe making sure that I start to read it below the row where the Start value is.我想读取数据帧中的文件,确保我开始在Start值所在的行下方读取它。

Attention : the Start value is not always located in the same row, so if I were to use:注意:在Start值并不总是位于同一行的,所以如果我是使用方法:

import pandas as pd
xls = pd.ExcelFile('C:\Users\MyFolder\MyFile.xlsx')
df = xls.parse('Sheet1', skiprows=4, index_col=None)

this would fail as skiprows needs to be fixed.这将失败, skiprows需要修复skiprows Is there any workaround to make sure that xls.parse finds the string value instead of the row number?是否有任何解决方法可以确保xls.parse找到字符串值而不是行号?

df = pd.read_excel('your/path/filename')

This answer helps in finding the location of 'start' in the df 答案有助于在 df 中找到“开始”的位置

 for row in range(df.shape[0]): 

       for col in range(df.shape[1]):

           if df.iat[row,col] == 'start':

             row_start = row
             break

after having row_start you can use subframe of pandas有了 row_start 后,您可以使用熊猫的子帧

df_required = df.loc[row_start:]

And if you don't need the row containing 'start', just u increment row_start by 1如果您不需要包含“start”的行,只需将 row_start 增加 1

df_required = df.loc[row_start+1:]

You could use pd.read_excel('C:\\Users\\MyFolder\\MyFile.xlsx', sheet_name='Sheet1') as it ignores empty excel cells.您可以使用pd.read_excel('C:\\Users\\MyFolder\\MyFile.xlsx', sheet_name='Sheet1')因为它会忽略空的 excel 单元格。

Your DataFrame should then look like this:您的 DataFrame 应如下所示:

    A      B     C
0   Start NaN   NaN
1   3      2     4
2   7      8     4
3   11     2     17

Then drop the first row by using然后使用删除第一行

df.drop([0])

to get得到

    A      B     C
0   3      2     4
1   7      8     4
2   11     2     17

如果您知道您感兴趣的特定行,您可以使用skiprow从顶部跳过,然后使用nrows仅解析您想要的行(或行) - 请参阅pandas.read_excel

df = pd.read_excel('myfile.xlsx', 'Sheet1', skiprows=2, nrows=3,)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM