【问题标题】:Reshaping tables in pandas在熊猫中重塑表格
【发布时间】:2013-05-23 15:52:27
【问题描述】:

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

                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 月)(即该月每天的标准化每日点击百分比)

【问题讨论】:

  • 我们很乐意提供帮助,但您没有发布任何代码或任何错误消息,因此不清楚您的问题是什么或让您感到困惑。
  • 感谢帝斯曼的反馈 - 刚刚编辑了问题以澄清。让我知道它是否仍然模棱两可。
  • 为了帮助其他人解决示例问题,请考虑更改问题的标题。 “旋转”意味着别的东西。也许是“熊猫的标准化计数?”
  • 感谢 Dan - 刚刚完成

标签: python arrays pandas dataframe


【解决方案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。

【讨论】:

  • Dan,我如何为每个关键字执行此操作(规范化)?最大。
  • 要单独按关键字执行,请将gropuby 的参数更改为'keyword'。要进行除 day 之外的按关键字细分的每日标准化,请使用列表作为参数:['keyword', lambda d: d.month]。 (这可能行不通——您可能需要将其拼写为 [daily_totals.keyword, lambda d: d.month]。)结果将根据日期和关键字进行多索引。
猜你喜欢
  • 1970-01-01
  • 2017-04-28
  • 2013-01-01
  • 2013-05-14
  • 2021-02-09
  • 1970-01-01
相关资源
最近更新 更多