如何迭代StyleFrame中的行?

2024-03-28 12:01:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我想通过迭代行来找到有颜色的单元格。你知道吗

enter image description here

我知道如何迭代列,但不知道如何迭代行。
在熊猫数据帧中

for i in range(0, len(df.index), 1):
    print(df.loc[i, 1])

但是StyleFrame没有loc。如何迭代并检查彩色单元格?你知道吗

谢谢!你知道吗


Tags: 数据indfforindexlen颜色range
1条回答
网友
1楼 · 发布于 2024-03-28 12:01:09

这里是StyleFrame维护程序。。。那是一个有趣的。。。你知道吗

这里的问题由两部分组成:

  • Pandasread_excel(StyleFrame使用)的默认行为是跳过空行。谢天谢地,它接受一个关键字参数来改变这个行为,StyleFrame的read_excel将它不知道的每个关键字参数传递给Pandas。因此,这个问题很容易解决:

    StyleFrame.read_excel('test.xlsx', read_style=True, skip_blank_lines=False)
    
  • 第二个问题/有问题的行为是openpyxl将背景未更改(或已设置为“自动”或“无填充”(取决于电子表格软件)的单元格的背景颜色设置为“000000”,即黑色。你知道吗

    这在StyleFrame中引入了一个bug,老实说,我不知道它是如何出现的。你知道吗

    要解决这个问题,您可以在StyleFrame的代码中做一些小的更改。线路#111英寸样式器.py(假设您使用的是StyleFrame的2.0.5版本)应该从

    bg_color = openpyxl_style.fill.fgColor.rgb
    

    bg_color = openpyxl_style.fill.fgColor.rgb if openpyxl_style.fill.patternType is not None else utils.colors.white
    

    此更改将包含在下一版本中。

然后,在解决了上述两个问题之后,解决实际问题就变得相对容易了(尽管不像我希望的那么容易):

from StyleFrame import StyleFrame, utils

def only_cells_with_colored_background(cell):
    return cell if cell.style.bg_color not in {utils.colors.white, 'FFFFFFFF'} else np.nan

sf = StyleFrame.read_excel('test.xlsx', read_style=True, skip_blank_lines=False)
sf = StyleFrame(sf.applymap(only_cells_with_colored_background).dropna(axis=(0, 1),
                how='all'))
print(sf)

将输出

   Unnamed: 0
2           a
3           b
4           c
9           a
10          b
11          c


我计划在将来的版本中实现一个.style访问器,所以希望上面的例子能像

sf = StyleFrame.read_excel('test.xlsx', read_style=True, skip_blank_lines=False)
sf = sf.loc[~(sf['Unnamed: 0'].style.bg_color == utils.colors.white)]

相关问题 更多 >