<p>我同意你的行为不理想。你知道吗</p>
<pre><code>>>> 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]"
</code></pre>
<p>您可以通过传递完全格式的<code>pandas.IndexSlice</code>作为子集参数来解决此问题:</p>
<pre><code>>>> df.style.format('{:.2f}', subset=pandas.IndexSlice[[3], :])
</code></pre>
<p>既然您询问了<code>_non_reducing_slice()</code>在做什么,那么它的目标是合理的(确保子集不会将维数降低为序列)。它的实现将列表视为一系列<em>列名</em>:</p>
<blockquote>
<p>From <a href="https://github.com/pandas-dev/pandas/blob/c0f6428b097f6e1a1765d8d07cb695169f442e66/pandas/core/indexing.py#L2477-L2506" rel="nofollow noreferrer">pandas/core/indexing.py</a>: </p>
<pre><code>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_]
...
</code></pre>
</blockquote>
<p>我想知道文档是否可以改进:在本例中,<code>subset=[3]</code>引发的异常与<code>df[[3]]</code>而不是<code>df.loc[[3]]</code>的行为匹配。你知道吗</p>