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(),我可以得到最近和最近的日期,但这仍然不能一条条地解决任务。任何帮助都将不胜感激!
发布于 2017-03-28 00:20:43
我使用idxmax来标识最大值的位置。这样就可以更容易地将其他相关数据保存在同一行中。
因此,ndf将是df的子集,其中每一行都包含一个score,这是['iP', 'date']组合中的最大值。然后,在该子集中,我再次标识哪些行包含每个iP的最新或最大的iP。最后,我用['iP', 'date', 'score']对结果进行了切片。
记住,这只是剥这只猫皮的一种方法。
ndf = df.loc[df.groupby(['iP', 'date']).score.idxmax()]
ndf.loc[ndf.groupby(['iP']).date.idxmax(), ['iP', 'date', 'score']]
iP date score
3 111.11.111.112 2016-04-05 10
4 111.11.111.113 2016-04-03 6
6 111.11.111.114 2016-04-03 7https://stackoverflow.com/questions/43058477
复制相似问题