首页 > 解决方案 > forLoop 除了标准是删除整行,我不想要

问题描述

让我从背景开始:我有一个数据框。这是一列超链接。我使用 forLoop 提取具有属性目标的超链接并将它们添加到附加列。

forLoop 成功的结果。

现在让我抛出曲线球:空白/间隙。假设列中有一个间隙并且源 C 不在图片中——那么 forLoop 会发生什么?

不需要的 forLoop 的结果

如果我不想删除行,而是希望 forLoop 在那里放置一个空白单元格,该怎么办?这样就不会重新排列任何数据,并且源 C 旁边有一个空白单元格或 NaN 单元格。那有意义吗?我有哪些选择?(另请注意,我的 print() 函数并没有真正按我的意愿工作。)对于它的价值,ws.cell 是一个访问 Excel 工作表单元格的 openpyxl 操作。

这是以防万一的硬代码:

links = []
for i in range(2, ws.max_row + 1):  # 2nd arg in range() not inclusive, so add 1
    try:
        links.append(ws.cell(row=i, column=1).hyperlink.target)
    except AttributeError or NaN:
        print('nothing here')

df['link'] = pd.Series(links)
df

标签: pythonpandasopenpyxl

解决方案


看不到您的输入数据,即输入 xlsx 文件,可能无法确定解决方案。无论如何,您是否尝试过以下操作?

...
except AttributeError or NaN:
    lists.append('')                      # still append a blank string to the list
    print('nothing here')

推荐阅读