在Pandas Dataframe中把负值标为红色,正值标为黑色

在Pandas Dataframe中把负值标为红色,正值标为黑色

让我们看看在Pandas Dataframe中突出正值为红色,负值为黑色的各种方法。
首先,让我们做一个Dataframe。

# Import Required Libraries
import pandas as pd
import numpy as np
  
  
# Create a dictionary for the dataframe
dict = {
  'Name': ['Sukritin', 'Sumit Tyagi', 
           'Akriti Goel', 'Sanskriti',
           'Abhishek Jain'],
   'Age': [22, 20, 45, 21, 22],
  'Marks': [90, 84, -33, -87, 82]
}
  
# Converting Dictionary to
# Pandas Dataframe
df = pd.DataFrame(dict)
  
# Print Dataframe
print(df)
Python

输出:

在Pandas Dataframe中把负值标为红色,正值标为黑色

现在,来看看突出显示的部分。我们的目标是将负值标为红色,正值标为黑色。

方法1:使用Dataframe.style.apply()

语法: DataFrame.style.apply(self, func, axis=0, subset=None, **kwargs)

参数:

  • func: 它应该接收一个基于axis的pandas.Series或pandas.DataFrame,并应该返回一个具有相同形状的对象。
  • axis: {0或’索引’,1或’列’,无},默认为0。适用于每一列(axis=0或’index’),适用于每一行(axis=1或’columns’),或者用axis=None一次适用于整个DataFrame。
  • subset: 你想在其中调用函数的列或行的集合。
  • kwargs: 传递给func。

例子1:突出显示文本。

# Define a function for colouring 
# negative values red and 
# positive values black
def highlight_max(s):
    if s.dtype == np.object:
        is_neg = [False for _ in range(s.shape[0])]
    else:
        is_neg = s < 0
    return ['color: red;' if cell else 'color:black' 
            for cell in is_neg]
  
# Using apply method of style 
# attribute of Pandas DataFrame
df.style.apply(highlight_max)
Python

输出:

在Pandas Dataframe中把负值标为红色,正值标为黑色

例子2:突出显示单元格而不是文本。

# Define a function which 
# returns the list for 
# df.style.apply() method
def highlight_max(s):
    if s.dtype == np.object:
        is_neg = [False for _ in range(s.shape[0])]
    else:
        is_neg = s < 0
    return ['background: red; color:white' 
            if cell else 'background:black; color:white' 
            for cell in is_neg]
  
# Using apply method of style 
# attribute of Pandas DataFrame
df.style.apply(highlight_max)
Python

输出:

在Pandas Dataframe中把负值标为红色,正值标为黑色

方法2:使用dataframe.style.applymap()方法。

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

参数:

  • func: 它接收一个标量值并返回标量值
  • subset: 你想调用该函数的列或行的集合。
  • **kwargs: 传递给func。

返回值: Styler对象。

例子1:突出显示文本。

# Define a function for 
# colouring negative values 
# red and positive values black
def highlight_max(cell):
    if type(cell) != str and cell < 0 :
        return 'color: red'
    else:
        return 'color: black'
  
df.style.applymap(highlight_max)
Python

输出:

在Pandas Dataframe中把负值标为红色,正值标为黑色

例子2:突出显示单元格而不是文本。

# Define a function which 
# returns string for 
# applymap() method
def highlight_max(cell):
    if type(cell) != str and cell < 0 :
        return 'background: red; color:black'
    else:
        return 'background: black; color: white'
  
df.style.applymap(highlight_max)
Python

输出:

在Pandas Dataframe中把负值标为红色,正值标为黑色

注意: pandas.DataFrame.applymap()方法只将单个单元格传递给可调用函数,而pandas.DataFrame.apply()则将pandas.Series传递给可调用函数。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册