📜  突出显示 Pandas Dataframe 中的 nan 值

📅  最后修改于: 2022-05-13 01:54:57.474000             🧑  作者: Mango

突出显示 Pandas Dataframe 中的 nan 值

在本文中,我们将讨论如何在 Pandas Dataframe 中突出显示 NaN(非数字)值。 NaN 值用于表示 NULL 值,有时它是数学溢出的结果。
让我们首先制作一个数据框:

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


Python3
# Highlighting cell with nan values
df.style.highlight_null('red')


Python3
# Highlighting text instead of the 
# cell's background
df.style.applymap(lambda cell: 'color:red' if pd.isnull(cell) else '')


Python3
# Highlighting text of the complete row
df.style.apply(lambda row: np.repeat('color: red' if row.isnull().any() else '',
                                     row.shape[0]), axis=1)


Python3
# Highlighting the complete row
df.style.apply(lambda row: np.repeat('background: red' if row.isnull().any() else '', row.shape[0]), axis=1)


Python3
# Highlighting column with nan values
df.style.apply(lambda row: np.repeat('background: red' if row.isnull().any() else '',
                                                                row.shape[0]), axis=0)


输出:

现在,来到突出显示部分。我们的目标是突出那些具有Nan值的单元格。

方法 1:使用 nan 值突出显示单元格

我们可以通过使用 DataFrame.style 属性的 highlight_null() 方法来做到这一点。这是一个返回 Styler 对象的属性,它具有格式化和显示 DataFrame 的有用方法。 highlight_null() 方法需要一个字符串参数(要突出显示单元格的颜色的名称)。

例子:

Python3

# Highlighting cell with nan values
df.style.highlight_null('red')

输出:

方法 2:使用 nan 值而不是背景突出显示文本

我们可以通过使用 style 属性的 applymap() 方法来做到这一点。 applymap() 方法需要一个接受标量并返回标量的函数。
例子:

Python3

# Highlighting text instead of the 
# cell's background
df.style.applymap(lambda cell: 'color:red' if pd.isnull(cell) else '')

输出:

方法3:用nan值高亮整行的文本

我们可以使用 apply() 方法来做到这一点
例子:

Python3

# Highlighting text of the complete row
df.style.apply(lambda row: np.repeat('color: red' if row.isnull().any() else '',
                                     row.shape[0]), axis=1)

输出:

方法 4:突出显示具有 nan 值的完整行

Python3

# Highlighting the complete row
df.style.apply(lambda row: np.repeat('background: red' if row.isnull().any() else '', row.shape[0]), axis=1)

输出:

解决方案 5:使用 nan 值突出显示整列

Python3

# Highlighting column with nan values
df.style.apply(lambda row: np.repeat('background: red' if row.isnull().any() else '',
                                                                row.shape[0]), axis=0)

输出: