python - Pandas 分组日期

标签 python pandas group-by

我有一个带有事件的 DataFrame。一个或多个事件可以在一个日期发生(因此日期不能是索引)。日期范围是几年。我想按年和月分组并计算类别值。谢谢

in [12]: df = pd.read_excel('Pandas_Test.xls', 'sheet1')
In [13]: df
Out[13]:
    EventRefNr     DateOccurence      Type Category
0        86596    2010-01-02 00:00:00     3    Small
1        86779    2010-01-09 00:00:00    13   Medium
2        86780    2010-02-10 00:00:00     6    Small
3        86781    2010-02-09 00:00:00    17    Small
4        86898    2010-02-10 00:00:00     6    Small
5        86898    2010-02-11 00:00:00     6    Small
6        86902    2010-02-17 00:00:00     9    Small
7        86908    2010-02-19 00:00:00     3   Medium
8        86908    2010-03-05 00:00:00     3   Medium
9        86909    2010-03-06 00:00:00     8    Small
10       86930    2010-03-12 00:00:00    29    Small
11       86934    2010-03-16 00:00:00     9    Small
12       86940    2010-04-08 00:00:00     9     High
13       86941    2010-04-09 00:00:00    17    Small
14       86946    2010-04-14 00:00:00    10    Small
15       86950    2011-01-19 00:00:00    12    Small
16       86956    2011-01-24 00:00:00    13    Small
17       86959    2011-01-27 00:00:00    17    Small

我试过:

df.groupby(df['DateOccurence'])

最佳答案

对于月份和年份的分割,我经常在数据框中添加额外的列,将日期分割为每一部分:

df['year'] = [t.year for t in df.DateOccurence]
df['month'] = [t.month for t in df.DateOccurence]
df['day'] = [t.day for t in df.DateOccurence]

与日期时间索引相比,它增加了空间复杂性(向 df 添加列)但时间复杂性较低(对 groupby 的处理较少),但这完全取决于您。日期时间索引是更多 pandas 做事的方式。

按年、月、日分组后,您可以根据需要进行任何分组。

df.groupby['year','month'].Category.apply(pd.value_counts)

要获得跨多年的月份:

df.groupby['month'].Category.apply(pd.value_counts)

或者在 Andy Hayden 的日期时间索引中

df.groupby[di.month].Category.apply(pd.value_counts)

您可以简单地选择更适合您需求的方法。

关于python - Pandas 分组日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19436365/

相关文章:

Pythonic 方式获取在 yaml 中定义或未定义的值

python - CNTK没有属性LeakyReLU

javascript - Python Flask Jinja2 网页在 location.reload(true) HTML Javascript 上没有完全刷新

python - Pandas Groupby 和 Sum Only 一列

pandas - 获取所有列的虚拟值

python - Pandas Dataframe 查找所有列都相等的行

python - 尝试读取存储在 Julia 的 HDF5 存储中的表作为数据框

c# - 带键的 LINQ groupby 语句

MySQL 按组最频繁的 SELECT

MySQL 查询与 GROUP BY 或 DISTINCT 相反吗?