subset参数在pandas.io.格式.style.Styler.format?

2024-03-29 11:31:49 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
2条回答

我同意你的行为不理想。你知道吗

>>> df = (pandas.DataFrame([dict(a=1,b=2,c=3),
                            dict(a=3,b=5,c=4)])
            .set_index('a'))
>>> df.loc[[3]]
   b  c
a      
3  5  4
>>> df.style.format('{:.2f}', subset=[3])
Traceback (most recent call last)
...
KeyError: "None of [Int64Index([3], dtype='int64')] are in the [columns]"

您可以通过传递完全格式的pandas.IndexSlice作为子集参数来解决此问题:

>>> df.style.format('{:.2f}', subset=pandas.IndexSlice[[3], :])

既然您询问了_non_reducing_slice()在做什么,那么它的目标是合理的(确保子集不会将维数降低为序列)。它的实现将列表视为一系列列名

From pandas/core/indexing.py:

def _non_reducing_slice(slice_):
    """
    Ensurse that a slice doesn't reduce to a Series or Scalar.

    Any user-paseed `subset` should have this called on it
    to make sure we're always working with DataFrames.
    """
    # default to column slice, like DataFrame
    # ['A', 'B'] -> IndexSlices[:, ['A', 'B']]
    kinds = (ABCSeries, np.ndarray, Index, list, str)
    if isinstance(slice_, kinds):
        slice_ = IndexSlice[:, slice_] 
    ...

我想知道文档是否可以改进:在本例中,subset=[3]引发的异常与df[[3]]而不是df.loc[[3]]的行为匹配。你知道吗

它确实做了它应该做的。你知道吗

df = pd.DataFrame(np.arange(16).reshape(4,4))

df.style.background_gradient(subset=[0,1])

df.style.background_gradient()

提供:

enter image description hereenter image description here

分别。你知道吗

相关问题 更多 >