簡體   English   中英

Python Pandas 樣式到每 n 行

[英]Python Pandas Style to every nth row

我正在開發一個帶有 Pandas 的 Python 項目,並希望每第 N 行實現一個樣式。 我已經能夠使用 iloc 每隔 N 行 select,但無法使該樣式與基本的 function 一起使用。 這是我在上下文中的示例:

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

此時一切都恢復正常,但是當應用下面的 function 時,我收到了太多索引錯誤,我似乎無法解決

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

任何幫助,將不勝感激。 謝謝你。

您一次將一行傳遞給 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)

如果df不是rangeIndex的索引,我將在axis=0上應用:

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)

Output:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM