python - 计算python数据框中每个日期的事件数

标签 python pandas

我正在尝试计算数据框中每个日期发生的事件数。我创建了一个新的数据框,其中的日期只出现一次,我将如何计算和汇总每个日期发生的事件。

到目前为止,我还没有找到合适的方法。

这是我拥有的数据示例:

date    event
01/01/10    1
01/01/10    1
01/01/10    2
02/01/10    1
04/01/10    3

我希望得到这个结果

date     event1 event2  event3
01/01/10    2     1      0
02/01/10    1     0      0
04/01/10    0     0      1

我们将不胜感激地欢迎任何建议

最佳答案

使用pd.crosstab:

pd.crosstab(df['date'], df['event'])

输出:

event      date  1  2  3
0      01/01/10  2  1  0
1      02/01/10  1  0  0
2      04/01/10  0  0  1

而且,我们可以像这样进行一些清理和重命名:

pd.crosstab(df['date'], df['event'])\
  .add_prefix('event')\
  .rename_axis(None, axis=1)\
  .reset_index()

输出:

       date  event1  event2  event3
0  01/01/10       2       1       0
1  02/01/10       1       0       0
2  04/01/10       0       0       1

关于python - 计算python数据框中每个日期的事件数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57076771/

相关文章:

python - 使用 PyMongo 进行词边界 RegEx 搜索

python - 根据日期连接 pandas 数据框

python - uWSGI 无法识别 --http 或 --wsgi-file 选项

python - 在opencv python中绘制直方图

python - 模块 'pandas' 没有属性 'expanding_max'

python - Django 管理操作 : generate actions for all choices with only one method

python - 将 pandas df 表转换或 reshape 为向量并重命名列

python - Pandas 分组并计算百分比,同时保留 NaN

python - matplotlib 的 plt.acorr 中自相关图的错误?

Python:根据DataFrame中的列名创建新行