📜  在Python中设置 Pandas 数据框背景颜色和字体颜色

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

在Python中设置 Pandas 数据框背景颜色和字体颜色

众所周知,样式背后的基本思想是使最终用户的可读性更具影响力。我们可以进行更改,例如可视化数据的颜色和格式,以便更有效地传达洞察力。为了对 pandas DataFrame 进行更有效的可视化,我们通常使用 DataFrame.style 属性,它返回 styler 对象,该对象具有许多用于格式化和可视化数据帧的有用方法。

使用 DataFrame.style 属性

  • df.style.set_properties:通过使用它,我们可以使用内置功能来操作从字体颜色到背景颜色的数据框样式。
Python3
# Importing the necessary libraries -->
import pandas as pd
import numpy as np
 
# Seeding random data from numpy
np.random.seed(24)
 
# Making the DataFrame
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4),
                                 columns=list('BCDE'))], axis=1)
 
# DataFrame without any styling
print("Original DataFrame:\n")
print(df)
print("\nModified Stlying DataFrame:")
df.style.set_properties(**{'background-color': 'black',
                           'color': 'green'})


Python3
# Replacing the locating value by NaN (Not a Number)
df.iloc[0, 3] = np.nan
df.iloc[2, 3] = np.nan
df.iloc[4, 2] = np.nan
df.iloc[7, 4] = np.nan
 
# Highlight the NaN values in DataFrame
print("\nModified Stlying DataFrame:")
df.style.highlight_null(null_color='red')


Python3
# Highlight the Min values in each column
print("\nModified Stlying DataFrame:")
df.style.highlight_min(axis=0)


Python3
# Highlight the Max values in each column
print("\nModified Stlying DataFrame:")
df.style.highlight_max(axis=0)


Python3
# function for set text color of positive
# values in Dataframes
def color_positive_green(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: green'` for positive
    strings, black otherwise.
    """
    if val > 0:
        color = 'green'
    else:
        color = 'black'
    return 'color: %s' % color
 
df.style.applymap(color_positive_green)


Python3
# Import seaborn library
import seaborn as sns
 
# Declaring the cm variable by the
# color palette from seaborn
cm = sns.light_palette("green", as_cmap=True)
 
# Visualizing the DataFrame with set precision
print("\nModified Stlying DataFrame:")
df.style.background_gradient(cmap=cm).set_precision(2)


Python3
# Highlight the NaN values in DataFrame
# using seaborn color palette
print("\nModified Stlying DataFrame:")
df.style.background_gradient(cmap=cm).set_precision(2).highlight_null('red')


Python3
# Highlight the NaN values in DataFrame
# using seaborn color palette as well as
# min('lighblue') and max('blue') values
# in each column
print("\nModified Stlying DataFrame:")
df.style.background_gradient(cmap=cm).set_precision(2).highlight_null('red').highlight_min(axis=0, color='lightblue').highlight_max(axis=0, color='blue')


输出:

df.style.set_properties

  • df.style.highlight_null :借助它,我们可以突出显示数据框中的缺失值或空值。

Python3

# Replacing the locating value by NaN (Not a Number)
df.iloc[0, 3] = np.nan
df.iloc[2, 3] = np.nan
df.iloc[4, 2] = np.nan
df.iloc[7, 4] = np.nan
 
# Highlight the NaN values in DataFrame
print("\nModified Stlying DataFrame:")
df.style.highlight_null(null_color='red')

输出:

df.style.highlight_null

  • df.style.highlight_min :用于突出显示整个数据框中每列的最小值。

Python3

# Highlight the Min values in each column
print("\nModified Stlying DataFrame:")
df.style.highlight_min(axis=0)

输出:

df.style.highlight_min

  • df.style.highlight_max :用于突出显示整个数据帧中每一列的最大值。

Python3

# Highlight the Max values in each column
print("\nModified Stlying DataFrame:")
df.style.highlight_max(axis=0)

输出:

df.style.highlight_max

使用自定义函数

  • 我们可以使用用户定义的函数来修改DataFrame:借助这个函数,我们可以自定义数据框内正数据值的字体颜色。

Python3

# function for set text color of positive
# values in Dataframes
def color_positive_green(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: green'` for positive
    strings, black otherwise.
    """
    if val > 0:
        color = 'green'
    else:
        color = 'black'
    return 'color: %s' % color
 
df.style.applymap(color_positive_green)

输出:

用户定义函数

使用 Seaborn 库

  • 在 DataFrame 中使用调色板进行渐变填充:通过从 seaborn 库中导入浅色调色板,我们可以为数据框的背景映射颜色渐变。

Python3

# Import seaborn library
import seaborn as sns
 
# Declaring the cm variable by the
# color palette from seaborn
cm = sns.light_palette("green", as_cmap=True)
 
# Visualizing the DataFrame with set precision
print("\nModified Stlying DataFrame:")
df.style.background_gradient(cmap=cm).set_precision(2)

输出:

Seaborn 调色板

  • 使用带有突出显示空值或缺失值的调色板:在这里,我们使用 seaborn 的渐变调色板以红色突出显示 NaN 值。

Python3

# Highlight the NaN values in DataFrame
# using seaborn color palette
print("\nModified Stlying DataFrame:")
df.style.background_gradient(cmap=cm).set_precision(2).highlight_null('red')

输出:

带有 highlight_null 的 Seaborn 调色板

  • 使用 DataFrame.style 属性组装 Seaborn 属性:使用数据框的突出显示属性自定义 seaborn 调色板,以实现更具影响力的数据可视化。

Python3

# Highlight the NaN values in DataFrame
# using seaborn color palette as well as
# min('lighblue') and max('blue') values
# in each column
print("\nModified Stlying DataFrame:")
df.style.background_gradient(cmap=cm).set_precision(2).highlight_null('red').highlight_min(axis=0, color='lightblue').highlight_max(axis=0, color='blue')

输出:

带有差异的 Seaborn 调色板。突出显示属性