首页 > 解决方案 > Pandas:使用合并的单元格和空白值解析 Excel 电子表格

问题描述

我的问题与类似。我有一个包含一些合并单元格的电子表格,但包含合并单元格的列也有空单元格,例如:

Day     Sample  CD4     CD8
----------------------------
Day 1   8311    17.3    6.44
        --------------------
        8312    13.6    3.50
        --------------------
        8321    19.8    5.88
        --------------------
        8322    13.5    4.09
----------------------------
Day 2   8311    16.0    4.92
        --------------------
        8312    5.67    2.28
        --------------------
        8321    13.0    4.34
        --------------------
        8322    10.6    1.95
----------------------------
        8323    16.0    4.92
----------------------------
        8324    5.67    2.28
----------------------------
        8325    13.0    4.34

如何将其解析为 Pandas DataFrame?我知道该fillna(method='ffill')方法不会解决我的问题,因为它会用其他东西替换实际缺失的值。我想得到一个像这样的DataFrame:

Day     Sample  CD4     CD8
----------------------------
Day 1   8311    17.3    6.44
----------------------------
Day 1   8312    13.6    3.50
----------------------------
Day 1   8321    19.8    5.88
----------------------------
Day 1   8322    13.5    4.09
----------------------------
Day 2   8311    16.0    4.92
----------------------------
Day 2   8312    5.67    2.28
----------------------------
Day 2   8321    13.0    4.34
----------------------------
Day 2   8322    10.6    1.95
----------------------------
NA      8323    16.0    4.92
----------------------------
NA      8324    5.67    2.28
----------------------------
NA      8325    13.0    4.34

标签: pythonexcelpandas

解决方案


假设您知道 excel 文件的起始行(或提出更好的检查方法),这样的事情应该可以工作

import pandas as pd
import numpy as np
import openpyxl
def test():
    filepath = "C:\\Users\\me\\Desktop\\SO nonsense\\PandasMergeCellTest.xlsx"
    df = pd.read_excel(filepath)
    wb = openpyxl.load_workbook(filepath)
    sheet = wb["Sheet1"]
    df["Row"] = np.arange(len(df)) + 2 #My headers were row 1 so adding 2 to get the row numbers
    df["Merged"] = df.apply(lambda x: checkMerged(x, sheet), axis=1)
    df["Day"] = np.where(df["Merged"] == True, df["Day"].ffill(), np.nan)
    df = df.drop(["Row", "Merged"], 1)
    print(df)

def checkMerged(x, sheet):
    cell = sheet.cell(x["Row"], 1)
    for mergedcell in sheet.merged_cells.ranges:
        if(cell.coordinate in mergedcell):
            return True

test()

推荐阅读