【问题标题】:Is there a way to read all the rows until an empty row is encountered using Python Pandas有没有办法使用 Python Pandas 读取所有行直到遇到空行
【发布时间】:2017-10-17 05:52:04
【问题描述】:

我在 excel 中有很多行,并且在空行之后这些行充满了垃圾值。 有没有办法使用 Python pandas 只读取 excel 中第一个空行之前的记录。

【问题讨论】:

    标签: python excel python-2.7 pandas


    【解决方案1】:

    我不知道 read_excel 是否可以做到这一点。如果从 excel 导入空行,这些行的列值将用 NaN 填充,然后您可以选择这些值,直到第一行用所有 NaN 填充。

    我假设你的数据是这样的,你有一个空行,后面的数据是垃圾(我包括了多个空行和后面的垃圾)

    df = pd.read_excel(r'Book1.xlsx') # read the file
    
    print df 
    '''
       col1 col2 col3
    0     1    2    3
    1     1    2    3
    2     1    2    3
    3     1    2    3
    ....
    10    1    2    3
    11  NaN  NaN  NaN
    12    x    x    x
    ....
    18  NaN  NaN  NaN
    19  NaN  NaN  NaN
    20    y    y    y
    21    y    y    y
    ....
    '''
    
    first_row_with_all_NaN = df[df.isnull().all(axis=1) == True].index.tolist()[0]
    # gives me the first row number of the row that has all the values to be NaN. 
    '''
    11
    '''
    
    print df.loc[0:first_row_with_all_NaN-1]
    
    # then I use loc to select the rows from 0 to  first row with all NaN's-1
    
    '''
     col1 col2 col3
    0     1    2    3
    1     1    2    3
    2     1    2    3
    3     1    2    3
    4     1    2    3
    5     1    2    3
    6     1    2    3
    7     1    2    3
    8     1    2    3
    9     1    2    3
    10    1    2    3
    '''
    

    【讨论】:

      猜你喜欢
      • 2016-06-20
      • 1970-01-01
      • 2021-09-21
      • 2013-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-15
      相关资源
      最近更新 更多