我的输入是这个简单的数据帧:

df = pd.DataFrame({'class': ['class_a', 'class_a', 'class_a', 'class_b', 'class_c', 'class_c'],
 'name': ['name_1', 'name_2', 'name_3', 'name_1', 'name_1', 'name_2'],
 'id': [5, 7, 1, 2, 3, 8]})
print(df)

     class    name  id
0  class_a  name_1   5
1  class_a  name_2   7
2  class_a  name_3   1
3  class_b  name_1   2
4  class_c  name_1   3
5  class_c  name_2   8

我想在列class中的每个组周围画一个蓝色实心边框(一个蓝色矩形).

我在堆栈溢出Pandas Style: Draw borders over whole row including the multiindex中找到了一个解决方案

s = df.style
for idx, group_df in df.groupby('class'):
    s = s.set_table_styles({group_df.index[0]: [{'selector': '', 'props': 'border-top: 3px solid blue;'}]}, 
                       overwrite=False, axis=1)

但有两个问题:

  1. 缺少外部边框
  2. 当我将其保存到EXCEL时,样式会丢失

enter image description here

有没有什么改变,伙计们,我们至少可以解决"第一点"?

推荐答案

要在CLASS列中的每个组周围绘制一个蓝色矩形,需要为分组的行设置上、下、左和右边框.这需要 for each 组的第一行和最后一行以及整个组设置边框.这可以实现如下所示

import pandas as pd

# Sample data
df = pd.DataFrame({
    'class': ['class_a', 'class_a', 'class_a', 'class_b', 'class_c', 'class_c'],
    'name': ['name_1', 'name_2', 'name_3', 'name_1', 'name_1', 'name_2'],
    'id': [5, 7, 1, 2, 3, 8]
})

def style_border_around_class_groups(df):
    # Get the start and end indices of each group
    start_indices = df.groupby('class').head(1).index
    end_indices = df.groupby('class').tail(1).index

    # Define a dictionary to store styles for each cell
    styles_dict = {}

    # For each row in the dataframe
    for i, row in df.iterrows():
        # Default styles
        top_border = ""
        bottom_border = ""
        left_border = ""
        right_border = ""

        # If the row index is a start index, add top border
        if i in start_indices:
            top_border = "3px solid blue"
        # If the row index is an end index, add bottom border
        if i in end_indices:
            bottom_border = "3px solid blue"

        # Apply horizontal borders to all columns
        for col in df.columns:
            styles_dict[(i, col)] = f"border-top: {top_border}; border-bottom: {bottom_border};"

        # Apply left border only to the first column
        styles_dict[(i, df.columns[0])] += "border-left: 3px solid blue;"

        # Apply right border only to the last column
        styles_dict[(i, df.columns[-1])] += "border-right: 3px solid blue;"

    # Apply the styles
    s = df.style.apply(lambda x: [styles_dict.get((x.name, col), "") for col in df.columns], axis=1)
    return s

# Apply the styling function
styled_df = style_border_around_class_groups(df)
styled_df

这导致了

Output image

Python相关问答推荐

Docker-compose:为不同项目创建相同的容器

在两极中实施频率编码

从单个列创建多个列并按pandas分组

将从Python接收的原始字节图像数据转换为C++ Qt QIcon以显示在QStandardProject中

Twilio:CallInstance对象没有来自_的属性'

ambda将时间戳与组内另一列的所有时间戳进行比较

具有多个选项的计数_匹配

使用mySQL的SQlalchemy过滤重叠时间段

根据不同列的值在收件箱中移动数据

修复mypy错误-赋值中的类型不兼容(表达式具有类型xxx,变量具有类型yyy)

如何在给定的条件下使numpy数组的计算速度最快?

所有列的滚动标准差,忽略NaN

Pandas—在数据透视表中占总数的百分比

移动条情节旁边的半小提琴情节在海运

在Python中,从给定范围内的数组中提取索引组列表的更有效方法

考虑到同一天和前2天的前2个数值,如何估算电力时间序列数据中的缺失值?

如何在Python中使用另一个数据框更改列值(列表)

将一个双框爆炸到另一个双框的范围内

pandas fill和bfill基于另一列中的条件

查看pandas字符列是否在字符串列中