使用 Pandas DataFrame 样式为列着色(Python 3)
Posted
技术标签:
【中文标题】使用 Pandas DataFrame 样式为列着色(Python 3)【英文标题】:Using Pandas DataFrame style to color a column (Python 3) 【发布时间】:2017-07-03 12:57:39 【问题描述】:我正在尝试按照http://pandas.pydata.org/pandas-docs/stable/style.html 上的教程为颜色列中我的熊猫数据框上的单元格的背景着色。
仅使用 pandas 的正确方法是什么?
s = """
num_markers num_contamination color
0 2.0 0.0 #db5f57
1 100.0 47.0 #db7157
2 104.0 102.0 #db8457
3 102.0 100.0 #db9657
4 NaN NaN #dba957
5 51.0 0.0 #dbbb57
6 NaN NaN #dbce57
7 92.0 63.0 #d6db57
8 NaN NaN #c4db57
9 56.0 42.0 #b1db57
"""
df = pd.read_clipboard() #Copy and paste then do this
D_idx_color = df["color"].to_dict()
df.style.apply(lambda x:"background-color: %s"%D_idx_color[x], subset=["color"])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/Users/jespinoz/anaconda/lib/python3.6/site-packages/IPython/core/formatters.py in __call__(self, obj)
309 method = get_real_method(obj, self.print_method)
310 if method is not None:
--> 311 return method()
312 return None
313 else:
/Users/jespinoz/anaconda/lib/python3.6/site-packages/pandas/formats/style.py in _repr_html_(self)
190 def _repr_html_(self):
191 """Hooks into Jupyter notebook rich display system."""
--> 192 return self.render()
193
194 def _translate(self):
/Users/jespinoz/anaconda/lib/python3.6/site-packages/pandas/formats/style.py in render(self)
415 the rendered HTML in the notebook.
416 """
--> 417 self._compute()
418 d = self._translate()
419 # filter out empty styles, every cell will have a class
/Users/jespinoz/anaconda/lib/python3.6/site-packages/pandas/formats/style.py in _compute(self)
481 r = self
482 for func, args, kwargs in self._todo:
--> 483 r = func(self)(*args, **kwargs)
484 return r
485
/Users/jespinoz/anaconda/lib/python3.6/site-packages/pandas/formats/style.py in _apply(self, func, axis, subset, **kwargs)
489 data = self.data.loc[subset]
490 if axis is not None:
--> 491 result = data.apply(func, axis=axis, **kwargs)
492 else:
493 result = func(data, **kwargs)
/Users/jespinoz/anaconda/lib/python3.6/site-packages/pandas/core/frame.py in apply(self, func, axis, broadcast, raw, reduce, args, **kwds)
4150 if reduce is None:
4151 reduce = True
-> 4152 return self._apply_standard(f, axis, reduce=reduce)
4153 else:
4154 return self._apply_broadcast(f, axis)
/Users/jespinoz/anaconda/lib/python3.6/site-packages/pandas/core/frame.py in _apply_standard(self, func, axis, ignore_failures, reduce)
4246 try:
4247 for i, v in enumerate(series_gen):
-> 4248 results[i] = func(v)
4249 keys.append(v.name)
4250 except Exception as e:
<ipython-input-155-3bf2a87dcd1f> in <lambda>(x)
14 df = pd.read_clipboard() #Copy and paste then do this
15 D_idx_color = df["color"].to_dict()
---> 16 df.style.apply(lambda x:"background-color: %s"%D_idx_color[x], subset=["color"])
/Users/jespinoz/anaconda/lib/python3.6/site-packages/pandas/core/generic.py in __hash__(self)
829 def __hash__(self):
830 raise TypeError('0!r objects are mutable, thus they cannot be'
--> 831 ' hashed'.format(self.__class__.__name__))
832
833 def __iter__(self):
TypeError: ("'Series' objects are mutable, thus they cannot be hashed", 'occurred at index color')
【问题讨论】:
【参考方案1】:我认为您不需要将颜色转换为字典,您可以使用 applymap
将您的功能应用于单个元素。
df.style.applymap(lambda x:"background-color: %s"%x, subset=['color'])
如果要根据color
列给所有元素上色,可以试试
def to_color(x):
return ["background-color: %s"%i for i in df.color]
df.style.apply(to_color, axis=0)
【讨论】:
啊伙计,我是如此接近。谢谢,这正是我想要完成的!以上是关于使用 Pandas DataFrame 样式为列着色(Python 3)的主要内容,如果未能解决你的问题,请参考以下文章