如何跳过着色 inf 值?
How to skip coloring inf values?
在 pandas 中处理后,我正在 excel 中设置一些数据的样式。但是我有一些坏数据给了我很多 inf 值。有没有办法跳过着色 inf 值?
cr = sns.light_palette("green", as_cmap=True)
styler = data.style
zeleno = styler.background_gradient(
cmap=cr,
subset=data.columns.get_loc_level('value1', level=1)[0]
)
styler.to_excel(writer, sheet_name=name)
我得到了这样的数据。
我需要这样,(跳过 inf 值,它们可以是白色或其他颜色)
目前,它仍然是一个更好的方法来使用apply
and implement this manually as, even with the addition of gmap
in 1.3.0, Styler.background_gradient不能支持单独的数据操作和显示以及子集。
要完成这项工作,我们需要完成两件事:
set_bad
确定如何处理“坏”值
- 确保
inf
被认为是“坏的”(它们不是)
确保 inf
被认为是坏的最简单的方法是 replace
inf
和 NaN
.
# Subset The DataFrame Before-Hand
cr = sns.light_palette("green", as_cmap=True)
# Set Bad to something like White
cr.set_bad('white')
def my_gradient(s, cmap):
return [f'background-color: {mcolors.rgb2hex(x)}'
for x in cmap(s.replace(np.inf, np.nan))]
# Use Subset Styler
styler = data.style
zeleno = styler.apply(
my_gradient,
cmap=cr, # Passed to function
subset=data.columns.get_loc_level('value1', level=1)[0],
axis=0 # (Default)
)
zeleno
*样式仅应用于子集(value1
on level=1)
设置和使用的导入:
import numpy as np
import pandas as pd # version 1.3.3
import seaborn as sns
from matplotlib import colors as mcolors
np.random.seed(25)
a = np.random.random((3, 4))
# Replace Randomly With inf
a[np.random.randint(0, 2, size=a.shape) == 0] = np.inf
data = pd.DataFrame(a, columns=pd.MultiIndex.from_product([
list('AB'),
['value1', 'value2']
]))
data
在 pandas 中处理后,我正在 excel 中设置一些数据的样式。但是我有一些坏数据给了我很多 inf 值。有没有办法跳过着色 inf 值?
cr = sns.light_palette("green", as_cmap=True)
styler = data.style
zeleno = styler.background_gradient(
cmap=cr,
subset=data.columns.get_loc_level('value1', level=1)[0]
)
styler.to_excel(writer, sheet_name=name)
我得到了这样的数据。
我需要这样,(跳过 inf 值,它们可以是白色或其他颜色)
目前,它仍然是一个更好的方法来使用apply
and implement this manually as, even with the addition of gmap
in 1.3.0, Styler.background_gradient不能支持单独的数据操作和显示以及子集。
要完成这项工作,我们需要完成两件事:
set_bad
确定如何处理“坏”值- 确保
inf
被认为是“坏的”(它们不是)
确保 inf
被认为是坏的最简单的方法是 replace
inf
和 NaN
.
# Subset The DataFrame Before-Hand
cr = sns.light_palette("green", as_cmap=True)
# Set Bad to something like White
cr.set_bad('white')
def my_gradient(s, cmap):
return [f'background-color: {mcolors.rgb2hex(x)}'
for x in cmap(s.replace(np.inf, np.nan))]
# Use Subset Styler
styler = data.style
zeleno = styler.apply(
my_gradient,
cmap=cr, # Passed to function
subset=data.columns.get_loc_level('value1', level=1)[0],
axis=0 # (Default)
)
zeleno
*样式仅应用于子集(value1
on level=1)
设置和使用的导入:
import numpy as np
import pandas as pd # version 1.3.3
import seaborn as sns
from matplotlib import colors as mcolors
np.random.seed(25)
a = np.random.random((3, 4))
# Replace Randomly With inf
a[np.random.randint(0, 2, size=a.shape) == 0] = np.inf
data = pd.DataFrame(a, columns=pd.MultiIndex.from_product([
list('AB'),
['value1', 'value2']
]))
data