Rad*_*tru 4 python excel python-3.x pandas
所以我有一个带有一些奇怪样式的 xls 文件,但我对此无能为力,所以我只需要解析它。
正如你所看到的,我有一些合并的单元格。我想要做的是填充合并单元格的空值(“ffill”),但也保持空单元格原样。
像这样的东西
EIM, C,NI1 Enescu_Ioan, EIM, S,NI11,Enescu_Ioan
EIM, C,NI1 Enescu_Ioan, Empty
EIM, C,NI1 Enescu_Ioan EIM, S,NI11,Enescu_Ioan
EIM, C,NI1,Enescu_Ioan Empty
我现在加载文件的方式是这样的。
xl = pd.ExcelFile("data/file.xls")
df = xl.parse(0, header=None)
Run Code Online (Sandbox Code Playgroud)
我也尝试像这样打开文件并访问合并的单元格,但我得到一个空列表。
book = xlrd.open_workbook("data/file.xls")
book.sheet_by_index(0).merged_cells # This is empty []
Run Code Online (Sandbox Code Playgroud)
我有什么办法可以实现这个目标吗?谢谢!
编辑
关于这个问题可能会有一些困惑,所以我会尽力解释得更好。附加图像是较大文件的子集,其中各列可能以不同的顺序出现。我想要实现的是一种区分合并单元格 NAN 值(在合并单元格中只有第一列有值,其余都是 nan)和空单元格 NAN 的方法。
设法找到修复方法
def read_excel(path):
excel = None
if path.endswith('xlsx'):
excel = pd.ExcelFile(xlrd.open_workbook(path), engine='xlrd')
elif path.endswith('xls'):
excel = pd.ExcelFile(xlrd.open_workbook(path, formatting_info=True), engine='xlrd')
else:
raise ValueError("Could not read this type of data")
return excel
def parse_excel(excel_file):
sheet_0 = excel_file.book.sheet_by_index(0)
df = excel_file.parse(0, header=None)
return sheet_0, df
def fill_merged_na(sheet, dataframe):
for e in sheet.merged_cells:
rl, rh, cl, ch = e
base_value = sheet.cell_value(rl, cl)
dataframe.iloc[rl:rh, cl:ch] = base_value
return dataframe
Run Code Online (Sandbox Code Playgroud)
一些重要的部分是打开 Excel 文件,并将formatting_info 设置为 True,以便还读取格式,例如合并的单元格和 fill_merged_na 函数,该函数仅填充合并的 nan 值,但保留初始的空单元格。
| 归档时间: |
|
| 查看次数: |
4999 次 |
| 最近记录: |