使用applymap()突出显示Pandas DataFrame的特定列

使用applymap()突出显示Pandas DataFrame的特定列

让我们看看如何突出Pandas DataFrame的元素和特定列。我们可以使用Styler类的applymap()函数来实现这一目标。

Styler.applymap()

语法 : Styler.applymap(self, func, subset = None, **kwargs)

参数 :

  • func : 接收一个标量并返回一个标量。
  • subset : 有效的索引器,在应用函数之前限制数据。
  • kwargs:传递给func的dict。

让我们用例子来理解。

首先,创建一个简单的数据框架。

# importing pandas as pd 
import pandas as pd 
  
# creating the dataframe  
df = pd.DataFrame({"A" : [14, 4, 5, 4, 1], 
                   "B" : [5, 2, 54, 3, 2],
                   "C" : [20, 20, 7, 3, 8],
                   "D" : [14, 3, 6, 2, 6]}) 
  
print("Original DataFrame :")
display(df)
Python

输出 :

使用applymap()突出显示Pandas DataFrame的特定列

示例1:对于数据框架中的每个单元格,如果数值小于6,那么我们将用红色突出显示该单元格,否则用蓝色。

# function definition
def highlight_cols(s):
    color = 'red' if s < 6 else 'blue'
    return 'background-color: % s' % color
  
# highlighting the cells
display(df.style.applymap(highlight_cols))
Python

输出 :

使用applymap()突出显示Pandas DataFrame的特定列

例子2:这次我们将只突出显示某些指定列中的单元格。

# function definition
def highlight_cols(s):
    return 'background-color: % s' % 'yellow'
  
# highlighting the cells
display(df.style.applymap(highlight_cols, 
                          subset = pd.IndexSlice[:, ['B', 'C']]))
Python

输出 :

使用applymap()突出显示Pandas DataFrame的特定列

在索引的帮助下,突出特定的列。

df.style.applymap(highlight_cols, subset = pd.IndexSlice[:, ['B', 'C']])
Python

使用applymap()突出显示Pandas DataFrame的特定列

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册