我有一些推特数据
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])
的操作吗?或者有更好的方法来做我想要的事情吗?
答案 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)