0

以下是我创建的合并多个查询日志数据框的数据框的摘录:

                keyword               hits         date         average time
1               the cat sat on        10           10-Jan       10
2               who is the sea        5            10-Jan       1.2
3               under the earth       30           1-Dec        2.5
4               what is this          100          1-Feb        9

有没有一种方法可以使用 Pandas 旋转数据,以便行是每日日期(例如 1 月 1 日、1 月 2 日等),每个日期对应的 1 列是每日点击总和(该点击总和)天,例如 1 月 1 日的点击总和)除以该月的每月点击总和(例如,整个 1 月)(即,该月每天的标准化每日点击百分比)

4

1 回答 1

1

解析日期,以便我们可以在以后提取月份。

In [99]: df.date = df.date.apply(pd.Timestamp)

In [100]: df
Out[100]: 
           keyword  hits                date  average time
1   the cat sat on    10 2013-01-10 00:00:00          10.0
2   who is the sea     5 2013-01-10 00:00:00           1.2
3  under the earth    30 2013-12-01 00:00:00           2.5
4     what is this   100 2013-02-01 00:00:00           9.0

按天分组并汇总点击数。

In [101]: daily_totals = df.groupby('date').hits.sum()

In [102]: daily_totals
Out[102]: 
date
2013-01-10     15
2013-02-01    100
2013-12-01     30
Name: hits, dtype: int64

按月分组,然后将每一行(每个每日总计)除以该月所有每日总计的总和。

In [103]: normalized_totals = daily_totals.groupby(lambda d: d.month).transform(lambda x: float(x)/x.sum())

In [104]: normalized_totals
Out[104]: 
date
2013-01-10    1
2013-02-01    1
2013-12-01    1
Name: hits, dtype: int64

您的简单示例每个月只给出一天,所以所有这些都是 1。

于 2013-05-23T18:05:08.013 回答