对于我的 html 表示的pandas数据帧(python),我想创建一些尽可能类似下面图片(用Excel创建)的东西,也就是给定一个序列数字,创建 INSIDE A TABLE ,一些水平条形图如果值大于零则变为绿色,如果它们低于零则为红色,并且轴上的“零”点根据动态重新调整为提供的数据。我最接近的是使用pandas本地乐器,由下面的代码给出(http://pandas.pydata.org/pandas-docs/stable/style.html)
#done in Jupyter
from pandas import DataFrame
df = pd.DataFrame([-0.02, 0.03, 0.04, -0.05], columns=['A'])
more_than_zero = df.loc[df.loc[:,'A'] >= 0].index.values.tolist()
less_than_zero = df.loc[df.loc[:,'A'] < 0].index.values.tolist()
df.style.bar(subset=pd.IndexSlice[more_than_zero,'A'], color='#d65f5f')
#df.style.bar(subset=pd.IndexSlice[less_than_zero, 'B'], color='#7fff00')
答案 0 :(得分:4)
现在没有办法使用pandas开箱即用(我会尽快实现),但现在这里是一个猴子修补解决方案:
def _bar_center_zero(self, s, color_positive, color_negative, width):
# Either the min or the max should reach the edge (50%, centered on zero)
m = max(abs(s.min()),abs(s.max()))
normed = s * 50 * width / (100 * m)
base = 'width: 10em; height: 80%;'
attrs_neg = (base+ 'background: linear-gradient(90deg, transparent 0%, transparent {w}%, {c} {w}%, '
'{c} 50%, transparent 50%)')
attrs_pos = (base+ 'background: linear-gradient(90deg, transparent 0%, transparent 50%, {c} 50%, {c} {w}%, '
'transparent {w}%)')
return [attrs_pos.format(c=color_positive, w=(50+x)) if x > 0
else attrs_neg.format(c=color_negative, w=(50+x))
for x in normed]
def bar_excel(self, subset=None, axis=0, color_positive='#5FBA7D',
color_negative='#d65f5f', width=100):
"""
Color the background ``color`` proptional to the values in each column.
Excludes non-numeric data by default.
.. versionadded:: 0.17.1
Parameters
----------
subset: IndexSlice, default None
a valid slice for ``data`` to limit the style application to
axis: int
color_positive: str
color_negative: str
width: float
A number between 0 or 100. The largest value will cover ``width``
percent of the cell's width
Returns
-------
self : Styler
"""
#subset = _maybe_numeric_slice(self.data, subset)
#subset = _non_reducing_slice(subset)
self.apply(self._bar_center_zero, axis=axis, subset=subset,
color_positive=color_positive, color_negative=color_negative,
width=width)
return self
将其修补到Styler类:
pd.formats.style.Styler._bar_center_zero = _bar_center_zero
pd.formats.style.Styler.bar_excel = bar_excel
现在你可以使用它了:
df = pd.DataFrame([-0.02, 0.03, 0.04, -0.05], columns=['A'])
df.style.bar_excel(color_positive='#5FBA7D', color_negative='#d65f5f')
此后我在GitHub上创建了一个pull request,我在其中实现了这一点以及“动态”(align='mid'
)居中的选项。
您可以通过指定选项align
并根据数据类型获得结果栏,如下所示: