【发布时间】:2017-03-29 01:54:24
【问题描述】:
import pandas as pd
import numpy as np
#Create sample df with following columns; iP,date,score,appOwner,color
df = pd.DataFrame(
{"iP":['111.11.111.112', '111.11.111.113', '111.11.111.112', '111.11.111.112', '111.11.111.113', '111.11.111.113', '111.11.111.114', '111.11.111.114', '111.11.111.114'],
"date":['2016-4-3', '2016-4-2', '2016-4-2', '2016-4-5', '2016-4-3', '2016-4-2', '2016-4-3', '2016-4-3', '2016-4-1'],
"score":[9, 8, 8, 10, 6, 7, 7, 7, 6],
"appOwner":['John','Andrew','Adam','John','Andrew','Adam','Park','Doe','Jason'],
"color":['Green','Yellow','Unknown','Red','White','Green','Red','Yellow','Red']
})
#Chage df['date'] dtype to datetime
df['date'] = pd.to_datetime(df['date'], format="%Y-%m-%d")
df
任务说明
在重复的 IP 中,选择最近的“日期”,然后选择得分最高(较高)的“iP”。 上面正确完成时所需的输出在下面,
ip date score
111.11.111.112 2016-4-5 10
111.11.111.113 2016-4-3 6
111.11.111.114 2016-4-3 7
我尝试过的
foo = df.groupby(['iP','date'])
bar = foo['score'].agg({'maxScore':np.max})
bar
maxScore
iP date
111.11.111.112 2016-04-02 8
2016-04-03 9
2016-04-05 10
111.11.111.113 2016-04-02 8
2016-04-03 6
111.11.111.114 2016-04-01 6
2016-04-03 7
我知道到目前为止我所尝试的方法并不能解决这个任务。
通过least_recent_date = df['date'].min()
recent_date = df['date'].max(),我可以获得最近和最近的日期,但这仍然不能一次性解决任务。
任何帮助将不胜感激!!
【问题讨论】: