Python 熊猫:使用合并单元格和空白值解析Excel电子表格
我的问题类似于。我有一个包含一些合并单元格的电子表格,但包含合并单元格的列也有空单元格,例如:Python 熊猫:使用合并单元格和空白值解析Excel电子表格,python,excel,pandas,Python,Excel,Pandas,我的问题类似于。我有一个包含一些合并单元格的电子表格,但包含合并单元格的列也有空单元格,例如: Day Sample CD4 CD8 ---------------------------- Day 1 8311 17.3 6.44 -------------------- 8312 13.6 3.50 -------------------- 8321 19.8 5.88
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
如何将其解析为数据帧?我知道fillna(method='ffill')
方法无法解决我的问题,因为它将用其他方法替换实际缺少的值。我想得到这样的数据帧:
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
假设您知道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()