擅长:python、mysql、java
<p>Groupby然后转移应该起作用:</p>
<pre><code># First, make sure your data is sorted from oldest to newest
df['date'] = pd.to_datetime(df['date'])
df.sort_values('date', inplace=True)
# Get previous event through groupby operation
df['prev_id'] = df.groupby('customerid')['eventid'].shift(1)
</code></pre>
<p>如果您想要每个客户的列表:</p>
<pre><code># create a dictionary with stored values – keys are customer id
prev_events_dict = df.groupby('customerid')['eventid'].apply(list).to_dict()
# map dict to dataframe
df['list_of_prev_id'] = df['customerid'].map(prev_events_dict)
</code></pre>