【问题标题】:python pandas task蟒蛇熊猫任务
【发布时间】:2021-11-09 13:08:13
【问题描述】:

我有一个这样的数据集

event_date | user_id | user_city | user_state |
06-09-2021 | 23      | Thane     | Maharashtra
04-09-2021 | 3224    | Madurai   | Tamil Nadu
02-08-2021 | 2331    | Ghaziabad | Utter Pradesh

使用 pandas python 我想以这种格式输出

User ID | Date of      | Location of  |  Location of  | Location on Second | 
        | Last Logins  | Latest Login |  Max Logins   | Most Login         |
        |              |              |               |                    |
5       | 11-09-2021   |  Gurgaon     |  Meerut       |  Noida             |


【问题讨论】:

  • 登录数据在哪里
  • 为什么需要登录数据
  • 在你的输出中你有登录数据,它不在原始表中
  • @trillion 我相信是原始数据,他可能会更改event_dateuser_city的列名
  • 到目前为止你有什么尝试?

标签: python pandas group-by


【解决方案1】:

您可以尝试使用pandas.DataFrame.nlargestpandas.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)

如果我的代码不符合您的预期结果,请告诉我。

【讨论】:

  • @LandLord 你能告诉我你遇到的错误吗?
猜你喜欢
  • 2016-10-16
  • 1970-01-01
  • 2021-02-18
  • 1970-01-01
  • 2018-11-07
  • 2013-10-19
  • 1970-01-01
  • 2015-03-23
  • 2021-08-04
相关资源
最近更新 更多