擅长:python、mysql、java
<p>如果需要获得第一行,我建议使用<code>.nth(0)</code>,而不是<code>.first()</code>。</p>
<p>它们之间的区别在于如何处理nan,因此无论这行中的值是什么,<code>.nth(0)</code>都将返回组的第一行,而<code>.first()</code>最终将返回每列中的第一个<strong>而不是</strong><code>NaN</code>值。</p>
<p>例如,如果您的数据集是:</p>
<pre><code>df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4],
'value' : ["first","second","third", np.NaN,
"second","first","second","third",
"fourth","first","second"]})
>>> df.groupby('id').nth(0)
value
id
1 first
2 NaN
3 first
4 first
</code></pre>
<p>以及</p>
<pre><code>>>> df.groupby('id').first()
value
id
1 first
2 second
3 first
4 first
</code></pre>