擅长:python、mysql、java
<p>从源代码来看,shape基本上使用了<code>len()</code>:
<a href="https://github.com/pandas-dev/pandas/blob/master/pandas/core/frame.py" rel="nofollow noreferrer">https://github.com/pandas-dev/pandas/blob/master/pandas/core/frame.py</a></p>
<pre><code>@property
def shape(self) -> Tuple[int, int]:
return len(self.index), len(self.columns)
</code></pre>
<pre><code>def __len__(self) -> int:
return len(self.index)
</code></pre>
<p>调用shape将尝试运行两个dim calc。所以也许<code>df.shape[0] + df.shape[1]</code>比<code>len(df.index) + len(df.columns)</code>慢。尽管如此,就性能而言,除了巨大的2D数据帧外,差异应该可以忽略不计。</p>
<p>因此,根据前面的答案,<code>df.shape</code>如果您需要两个维度,那么对于单个维度,<code>len()</code>在概念上似乎更合适。</p>
<p>看看<a href="https://stackoverflow.com/questions/1142133/python-property-versus-method-performance-which-one-to-use">property vs method</a>答案,它都指向代码的可用性和可读性。因此,在您的例子中,我想说,如果您只想检查整个数据帧的信息,或者例如要将形状元组传递给函数,请使用<code>shape</code>。对于单个列,包括<em>index</em>(即df的行),使用<code>len()</code>。</p>