使用Agg查找每天最常用的用户

时间:2016-05-30 17:33:38

标签: python pandas dataframe group-by

我有一些推特数据

username    time
RamiAlLolah 2016-03-11
grezz10     2016-02-19
DawlaWitness11  2016-04-08
murasil1    2016-04-29
mustaklash  2016-02-19

我希望能够确定谁是每天最频繁的高音扬声器。我可以按天数对数据框进行分组,然后使用df.username.value_counts().reset_index().ix[0,0]来获取当天最频繁的推文。

我可以使用agg为整个数据框执行此操作吗?要找到每天最常用的高音扬声器,我可以执行类似r.agg( lambda x: x.username.value_counts().reset_index().ix[0,0])的操作吗?或者有更好的方法来做我想要的事情吗?

2 个答案:

答案 0 :(得分:0)

我认为您可以groupby使用dt.date汇总mode和上次reset_index

print (df.username.groupby(df.time.dt.date).apply(lambda x: x.mode()))

样品:

import pandas as pd

df = pd.DataFrame({'time': {0: pd.Timestamp('2016-03-11 00:00:00'), 1: pd.Timestamp('2016-02-19 00:00:00'), 2: pd.Timestamp('2016-02-19 00:00:00'), 3: pd.Timestamp('2016-02-19 00:00:00'), 4: pd.Timestamp('2016-04-08 00:00:00'), 5: pd.Timestamp('2016-04-08 00:00:00'), 6: pd.Timestamp('2016-04-29 00:00:00'), 7: pd.Timestamp('2016-02-19 00:00:00')}, 
                   'username': {0: 'RamiAlLolah', 1: 'grezz10', 2: 'grezz10', 3: 'grezz10', 4: 'DawlaWitness11', 5: 'DawlaWitness11', 6: 'murasil1', 7: 'mustaklash'}},
                    columns = ['username','time'])
print (df)
         username       time
0     RamiAlLolah 2016-03-11
1         grezz10 2016-02-19
2         grezz10 2016-02-19
3         grezz10 2016-02-19
4  DawlaWitness11 2016-04-08
5  DawlaWitness11 2016-04-08
6        murasil1 2016-04-29
7      mustaklash 2016-02-19

print (df.username.groupby(df.time.dt.date)
                  .apply(lambda x: x.mode())
                  .reset_index(drop=True, level=1)
                  .reset_index())

         time        username
0  2016-02-19         grezz10
1  2016-04-08  DawlaWitness11

答案 1 :(得分:0)

另一个解决方案是采用每次模式和连续解决方案

r = pd.concat([df[df.time == i].mode() for i in df.time.unique()])

可选您可以做的索引(因为您更喜欢结果)

r = r.reset_index(drop=True)

r.set_index('time', inplace = True)