python - 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
解决方案
假设您知道 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()
推荐阅读
- python - suds 3 `__inject` 引发 AttributeError:“NoneType”对象没有属性“promotePrefixes”
- swift - 在 Mapbox 中设置预定义的纬度和经度,而不是点击位置
- javascript - 单击 div 时将 div 内的文本复制到剪贴板
- .net-core - VSTS dotnet 运行步骤未找到上一步的构建
- testng - 软断言和验证之间的区别
- sql - 将 JD Edwards 编号列格式化为 HH24:MI:SS
- iis-7 - 如何在 2 个 IIS 服务器内共享哈希表
- r - 如何从 R 中的 30 个 fasta 文件创建 SQLite 数据库?
- python - 在 python 中使用 zip() 时如何确保所有文件都已成功压缩,是否有任何功能可以检查或确认?
- netsuite - 如何更新刚刚创建的交易的自定义列字段