您可以尝试使用pandas.DataFrame.nlargest 和pandas.Series.value_counts,并在应用pandas.DataFrame.groupby 和新列名后返回pandas.Series。
import pandas as pd
df = pd.DataFrame([
['06-28-2021',23 ,'Thane','Maharashtra'],
['06-12-2021',23 ,'TEST','Maharashtra'],
['06-11-2021',23 ,'TEST','Maharashtra'],
['04-09-2021',3224,'Madurai','Tamil Nadu'],
['02-08-2021',2331,'Ghaziabad','Utter Pradesh']],
columns=['event_date', 'user_id', 'user_city', 'user_state'])
df['event_date'] = pd.to_datetime(df['event_date'])
def func(g):
last_row = g.iloc[-1]
cities = g['user_city'].value_counts().nlargest(2).index
cols = ['Date of last login','Location of Latest Logins','Location of Last Logins','Location on Second Most Login']
return pd.Series((last_row['event_date'],last_row['user_city'],cities[0],cities[-1]), index=cols)
new_df = df.sort_values('event_date').groupby('user_id').apply(func)
print(new_df)
| user_id |
Date of last login |
Location of last login |
Location of most login |
Location on 2nd Most Login |
| 23 |
2021-06-28 00:00:00 |
Thane |
TEST |
Thane |
| 2331 |
2021-02-08 00:00:00 |
Ghaziabad |
Ghaziabad |
Ghaziabad |
| 3224 |
2021-04-09 00:00:00 |
Madurai |
Madurai |
Madurai |
方法 2
使用pandas.DataFrame.nlargest 获取最大日期而不对数据框进行排序(即您可以避免使用df.sort_values('event_date'))
注意:在某些情况下 sort_values 会更快,以避免在每次迭代中访问 nlargest 的开销。
def func(g):
last_login = df.iloc[g['event_date'].nlargest(1).index[0]]
cities = g['user_city'].value_counts().nlargest(2).index
cols = ['Date of last login','Location of Latest Logins','Location of Last Logins','Location on Second Most Login']
return pd.Series((last_login['event_date'],last_login['user_city'],cities[0],cities[-1]), index=cols)
如果我的代码不符合您的预期结果,请告诉我。