简体   繁体   English

Pandas 数据框样式:根据格式列突出显示一些单元格

[英]Pandas dataframe styling: highlight some cells based on a format column

Problem description问题描述

I have a DataFrame in which last column is a format column.我有一个 DataFrame,其中最后一列是格式列。 The purpose of this column is to contain the format of the DataFrame row.此列的目的是包含 DataFrame 行的格式。 Here is an example of such a dataframe:这是此类数据框的示例:

df = pd.DataFrame({'ID': [1, 24, 31, 37],
                   'Status': ['to analyze', 'to analyze','to analyze','analyzed'],
                   'priority' : ['P1','P1','P2','P1'],
                   'format' : ['n;y;n','n;n;n','n;y;y','y;n;y']}

Each df['format'] row contains a string intended to be taken as a list (when split) to give the format of the row.每个 df['format'] 行都包含一个字符串,旨在作为列表(拆分时)给出行的格式。

Symbols meaning:符号含义:

  • n means "no highlight" n 表示“没有亮点”
  • y means "to highlight in yellow" y 表示“以黄色突出显示”

df['format'].to_list()[0] = 'n;y;n' means for example: df['format'].to_list()[0] = 'n;y;n' 表示例如:

  • n: first column ID item "1" not highlighted n:未突出显示第一列 ID 项“1”
  • y: second column Status item "to analyze" to be highlighted y:要突出显示的第二列状态项“要分析”
  • n: third column Priority item "P1" not highlighted n:第三列优先项“P1”未突出显示

So that expected outcome is:所以预期的结果是:

预期结果

What I've tried我试过的

I've tried to use df.format to get a list of lists containing the format needed.我尝试使用 df.format 来获取包含所需格式的列表列表。 Here is my code:这是我的代码:

import pandas as pd
import numpy as np

def highlight_case(df):
    list_of_format_lists = []
    for format_line in df['format']:
        format_line_list = format_line.split(';')
        format_list = []
        for form in format_line_list:
            if 'y' in form:
                format_list.append('background-color: yellow')
            else:
                format_list.append('')
        list_of_format_lists.append(format_list)
    list_of_format_lists = list(map(list, zip(*list_of_format_lists)))#transpose
    print(list_of_format_lists)
    return list_of_format_lists


highlight_style = highlight_case(df)
df.style.apply(highlight_style)

It doesn't work, and I get this output:它不起作用,我得到了这个输出:

TypeError                                 Traceback (most recent call last)
c:\python38\lib\site-packages\IPython\core\formatters.py in __call__(self, obj)
    343             method = get_real_method(obj, self.print_method)
    344             if method is not None:
--> 345                 return method()
    346             return None
    347         else:

c:\python38\lib\site-packages\pandas\io\formats\style.py in _repr_html_(self)
    191         Hooks into Jupyter notebook rich display system.
    192         """
--> 193         return self.render()
    194 
    195     @doc(NDFrame.to_excel, klass="Styler")

c:\python38\lib\site-packages\pandas\io\formats\style.py in render(self, **kwargs)
    538         * table_attributes
    539         """
--> 540         self._compute()
    541         # TODO: namespace all the pandas keys
    542         d = self._translate()

c:\python38\lib\site-packages\pandas\io\formats\style.py in _compute(self)
    623         r = self
    624         for func, args, kwargs in self._todo:
--> 625             r = func(self)(*args, **kwargs)
    626         return r
    627 

c:\python38\lib\site-packages\pandas\io\formats\style.py in _apply(self, func, axis, subset, **kwargs)
    637         data = self.data.loc[subset]
    638         if axis is not None:
--> 639             result = data.apply(func, axis=axis, result_type="expand", **kwargs)
    640             result.columns = data.columns
    641         else:

c:\python38\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, raw, result_type, args, **kwds)
   7543             kwds=kwds,
   7544         )
-> 7545         return op.get_result()
   7546 
   7547     def applymap(self, func) -> "DataFrame":

c:\python38\lib\site-packages\pandas\core\apply.py in get_result(self)
    142         # dispatch to agg
    143         if is_list_like(self.f) or is_dict_like(self.f):
--> 144             return self.obj.aggregate(self.f, axis=self.axis, *self.args, **self.kwds)
    145 
    146         # all empty

c:\python38\lib\site-packages\pandas\core\frame.py in aggregate(self, func, axis, *args, **kwargs)
   7353         axis = self._get_axis_number(axis)
   7354 
-> 7355         relabeling, func, columns, order = reconstruct_func(func, **kwargs)
   7356 
   7357         result = None

c:\python38\lib\site-packages\pandas\core\aggregation.py in reconstruct_func(func, **kwargs)
     74 
     75     if not relabeling:
---> 76         if isinstance(func, list) and len(func) > len(set(func)):
     77 
     78             # GH 28426 will raise error if duplicated function names are used and

TypeError: unhashable type: 'list'

Since the formats are encoded for each row, it makes sense apply row-wise:由于格式是为每一行编码的,因此按行apply是有意义的:

def format_row(r):
    formats = r['format'].split(';')
    return ['background-color: yellow' if y=='y' else '' for y in formats] + ['']

df.style.apply(format_row, axis=1)

Output:输出:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据 Pandas 中的行和列值突出显示单元格? - How can I highlight cells based on row and column values in Pandas? Python pandas数据框到html - 根据标题值突出显示整个列 - Python pandas dataframe to html — highlight entire column based on header value 基于 Python Pandas 中列中的值突出显示 DataFrame 中的行 - Highlight rows from a DataFrame based on values in a column in Python Pandas pandas + xlsx:根据另一个数据框格式化单元格 - pandas+xlsx: format cells based on another dataframe 如何通过每列的不同条件突出显示 dataframe 中的某些单元格? 是否也可以突出显示系列中的某些数字? - How to highlight some cells in a dataframe through different condition for each column? Is also possible highlighting some number in a Series? 突出显示列表中包含的 pandas dataframe 单元格 - Highlight pandas dataframe cells contained in a list 如何根据上一列填充 Pandas 数据框中的 NaN 单元格? - How to fill NaN cells in a pandas dataframe, based on the previous column? 根据另一个dataFrame的某些列值制作一个熊猫dataFrame - Making a pandas dataFrame based on some column values of another dataFrame 根据另一个数据框中的列有条件地格式化每列中的单元格 - Conditionally format cells in each column based on columns in another dataframe 如何根据某些条件连接熊猫列中的两个单元格? - how to concatenate two cells in a pandas column based on some conditions?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM