第n行的Python Pandas样式

问题描述 投票:0回答:2

我正在开发一个带有Pandas的Python项目,并希望为每N行实现一种样式。我已经能够使用iloc选择第N行,但是无法使用基本功能使用该样式。这是我在上下文中的示例:

data = [[1,2,3],[2,3,4],[3,4,5],[4,5,6]]
df = pd.DataFrame(data)
df
   0  1  2
0  1  2  3
1  2  3  4
2  3  4  5
3  4  5  6
df.iloc[1::2, :]
   0  1  2
1  2  3  4
3  4  5  6

此时一切恢复正常,但是应用以下功能时,我收到了太多索引错误,似乎无法解决

def highlight_everyother(s):
    if s.iloc[1::2, :]:
        return ['background-color: yellow']*3

df.style.apply(highlight_everyother, axis=1)

ERROR:

IndexingError                             Traceback (most recent call last)
~\Anaconda3\lib\site-packages\IPython\core\formatters.py in __call__(self, obj)
    343             method = get_real_method(obj, self.print_method)
    344             if method is not None:
--> 345                 return method()
    346             return None
    347         else:

~\Anaconda3\lib\site-packages\pandas\io\formats\style.py in _repr_html_(self)
    180         Hooks into Jupyter notebook rich display system.
    181         """
--> 182         return self.render()
    183 
    184     @Appender(

~\Anaconda3\lib\site-packages\pandas\io\formats\style.py in render(self, **kwargs)
    535         * table_attributes
    536         """
--> 537         self._compute()
    538         # TODO: namespace all the pandas keys
    539         d = self._translate()

~\Anaconda3\lib\site-packages\pandas\io\formats\style.py in _compute(self)
    610         r = self
    611         for func, args, kwargs in self._todo:
--> 612             r = func(self)(*args, **kwargs)
    613         return r
    614 

~\Anaconda3\lib\site-packages\pandas\io\formats\style.py in _apply(self, func, axis, subset, **kwargs)
    618         data = self.data.loc[subset]
    619         if axis is not None:
--> 620             result = data.apply(func, axis=axis, result_type="expand", **kwargs)
    621             result.columns = data.columns
    622         else:

~\Anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, raw, result_type, args, **kwds)
   6876             kwds=kwds,
   6877         )
-> 6878         return op.get_result()
   6879 
   6880     def applymap(self, func) -> "DataFrame":

~\Anaconda3\lib\site-packages\pandas\core\apply.py in get_result(self)
    184             return self.apply_raw()
    185 
--> 186         return self.apply_standard()
    187 
    188     def apply_empty_result(self):

~\Anaconda3\lib\site-packages\pandas\core\apply.py in apply_standard(self)
    311 
    312         # compute the result using the series generator
--> 313         results, res_index = self.apply_series_generator()
    314 
    315         # wrap results

~\Anaconda3\lib\site-packages\pandas\core\apply.py in apply_series_generator(self)
    339         else:
    340             for i, v in enumerate(series_gen):
--> 341                 results[i] = self.f(v)
    342                 keys.append(v.name)
    343 

<ipython-input-49-a5b996f8d6c8> in highlight_everyother(s)
     11 
     12 def highlight_everyother(s):
---> 13     if s.iloc[1::2, :]:
     14         return ['background-color: yellow']*3
     15 

~\Anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
   1760                 except (KeyError, IndexError, AttributeError):
   1761                     pass
-> 1762             return self._getitem_tuple(key)
   1763         else:
   1764             # we by definition only have the 0th axis

~\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup)
   2065     def _getitem_tuple(self, tup: Tuple):
   2066 
-> 2067         self._has_valid_tuple(tup)
   2068         try:
   2069             return self._getitem_lowerdim(tup)

~\Anaconda3\lib\site-packages\pandas\core\indexing.py in _has_valid_tuple(self, key)
    699         for i, k in enumerate(key):
    700             if i >= self.ndim:
--> 701                 raise IndexingError("Too many indexers")
    702             try:
    703                 self._validate_key(k, i)

IndexingError: Too many indexers

任何帮助将不胜感激。谢谢。

python pandas dataframe
2个回答
0
投票

您一次将一行传递给highlight_everyother。这就是为什么您得到错误。下面应该工作。

def highlight_everyother(s):
    if s.name%2==1:
        return ['background-color: yellow']*3
    else:
        return ['background-color: white']*3

df.style.apply(highlight_everyother, axis=1)

0
投票

如果axis=0未被df索引,我会在rangeIndex上提出申请:

def highlight_everyother(s):
    return ['background-color: yellow; color:blue' if x%2==1 else ''
              for x in range(len(s))]

df.style.apply(highlight_everyother)

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.