Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Pandas DataFrame style to color a column (Python 3)

I'm trying to follow the tutorial on http://pandas.pydata.org/pandas-docs/stable/style.html to color the background of the cells on my pandas dataframe in the color column.

What is the proper way to do this using only 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')
like image 316
O.rka Avatar asked Dec 24 '22 20:12

O.rka


1 Answers

I think you don't need to convert color to dictionary, you can just use applymap to apply your function to individual element.

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

Jupyter Ouput

If you want to color all the elements according to the color column, you can try

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

Jupyter output

like image 68
SSC Avatar answered Dec 26 '22 19:12

SSC