擅长:python、mysql、java
<p>或者,在没有循环的情况下,使用<code>pd.DataFrame.groupby</code>:</p>
<pre><code>date1 = list(test2.groupby("product")["Date"].apply(lambda x: x.iloc[-2])
date2 = list(test2.groupby("product")["Date"].apply(lambda x: x.iloc[-3])
</code></pre>
<p><strong>编辑</strong></p>
<p>或者,正如@yatu所指出的,更好的是,您还可以利用<code>nth</code>:</p>
<pre><code>date1 = list(test2.groupby("product")["Date"].nth(-2))
date2 = list(test2.groupby("product")["Date"].nth(-3))
</code></pre>