查找数据帧pandas中第一个空行的索引值

2024-10-01 15:42:49 发布

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

我正在用熊猫看一张纸。读完工作表后,我得到的值之间有一个空行。在

所以,我需要找到该行的索引值并删除该行下面的所有行,然后生成一个新的数据帧。在

from xlrd import open_workbook

import pandas as pd

from pandas import ExcelWriter

pathbook = open_workbook("S:\\1. DIRECTORY MASTER\\FINANCIAL RESEARCH\\Data 
Initiative - PROJECTS\\Market Rollout\\"
                     "Modified Files\\2016\\2016A-3032 - CA.xlsx")
pathbook_sheet = pathbook.sheet_by_name("1-Rollout")

file = "S:\\1. DIRECTORY MASTER\\FINANCIAL RESEARCH\\Data Initiative - 
PROJECTS\\Market Rollout\\" \
   "Modified Files\\2016\\2016A-3032 - CA.xlsx"

for rowidx in range(pathbook_sheet.nrows):
    row = pathbook_sheet.row(rowidx)
    for colidx, cell in enumerate(row):
        if cell.value == "Canadian Market":
            print("Sheet Name:", pathbook_sheet.name)
            print("Row Number:", rowidx)
            CADvalue = int(rowidx)
            CADvalue += 1

print(CADvalue)
reading_book = pd.read_excel(file, sheet_name="1-Rollout", 
skiprows=CADvalue, index_col=0).iloc[:12]

write = ExcelWriter("Final" + ".xlsx")
reading_book.to_excel(write, 'Sheet1', index=False)
write.save()

我得到的excel文件中的示例输出

Sales 2016 2017 2018 2019 2020 2021 Units Sold 0 0 0 4 14 37 Unit Sale Price 1285 1285 1285 1285 1285 1285 Unit Profit 4000 4000 4000 4000 4000 4000
Rest of the World Market

所以最后3行之间有一个空行


Tags: namefromimportxlsxexcelmarketwritesheet
2条回答
#First, find NaN entries in first column
blank_row_bool = reading_book.iloc[:,1].isna()
#Next, get index of first NaN entry
blank_row_index =  [i for i, x in enumerate(blank_row_bool) if x][0]
#Finally, restrict dataframe to rows before the first NaN entry
reading_book = reading_book.iloc[:(blank_row_index-1)]

或者,在一行中:

^{pr2}$

解决办法取决于空意味着什么。如果它只是一个空字符串,如'',则查找索引的代码为:

empty = ''
idx_first_empty_row = reading_book.index[reading_book.iloc[:, 0] == empty][0]

如果第一列为空,则此操作有效。例如,如果“empty”表示NaN,则将该行替换为:

^{pr2}$

如果行的dtype是任何数字numpy类型,比如np.float64,那么这就可以了。在

如果dtype不是任何numpy数字类型,请尝试以下操作:

idx_first_empty_row = np.where(reading_book.iloc[:, 0].isnull().values == True)

根据行中的数据类型,也可以尝试以下操作:

idx_first_empty_row = reading_book.index[reading_book.iloc[:, 0].isnull().values]

相关问题 更多 >

    热门问题