gpt4 book ai didi

pandas - 使用 Pandas DataFrame 样式为列着色 (Python 3)

转载 作者:行者123 更新时间:2023-12-02 06:49:38 30 4
gpt4 key购买 nike

我正在尝试按照 http://pandas.pydata.org/pandas-docs/stable/style.html 上的教程进行操作为颜色列中我的 pandas 数据框上的单元格背景着色。

仅使用 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')

最佳答案

我认为你不需要将颜色转换为字典,你只需使用applymap将你的函数应用到单个元素。

df.style.applymap(lambda x:"background-color: %s"%x, subset=['color'])

Jupyter Ouput

如果你想根据color列给所有元素着色,你可以尝试

def to_color(x):
return ["background-color: %s"%i for i in df.color]
df.style.apply(to_color, axis=0)

Jupyter output

关于pandas - 使用 Pandas DataFrame 样式为列着色 (Python 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42239657/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com