我有一个数据框,包含一个月的文本,并带有时间戳,类似于:

timestamp              text
2023-01-01 00:00:00    ABC
2023-01-01 00:00:01    DEF
2023-01-01 00:00:01    GHI
...

我想计算一周中每小时和每一天的文本数量,所以最后有168(24*7)个数字.

例如,如果2023-01-01,也就是周日,上午10点到11点之间有10条短信,那么下个周日(2023-01-08)总是在上午10点到11点之间有15条短信,以此类推.在结束时,所有周日上午10点到11点的文本数量是:10+15+...

我想在一周中的每一小时和每一天都这样做.

如果原始数据帧是df,我开始按小时分组:

hours_df = df.groupby(pd.Grouper(key="timestamp", freq="h")).size().reset_index(name="count_hours")

然后我加了day_of_week:

hours_df["day_of_week"] = hours_df["timestamp"].dt.dayofweek

但如果我现在以day_of_week为单位进行分组:

day_df = hours_df.groupby("day_of_week").size().reset_index(name="count_days")

我将丢失有关小时数的信息,结果是一个包含7个条目的数据帧,即天数.

我怎样才能把时间分组和天分组结合起来呢?

推荐答案

您可以直接按星期和小时分组:

df.groupby([df['timestamp'].dt.dayofweek.rename('dow'),
            df['timestamp'].dt.hour.rename('hour')
           ]).size()

或使用concatvalue_counts:

pd.concat([df['timestamp'].dt.dayofweek.rename('dow'),
           df['timestamp'].dt.hour.rename('hour')], axis=1
         ).value_counts()

输出:

dow  hour
6    0       3
dtype: int64

NB. for a long enough input, you should have all combinations, if not you can always 100.


或者,对于矩形输出,使用crosstab:

pd.crosstab(df['timestamp'].dt.dayofweek.rename('dow'),
            df['timestamp'].dt.hour.rename('hour'))

# or for all values:
out = (pd.crosstab(df['timestamp'].dt.dayofweek.rename('dow'),
                   df['timestamp'].dt.hour.rename('hour'))
         .reindex(index=range(1, 7), columns=range(24), fill_value=0)
      )

输出:

hour  0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18  19  20  21  22  23
dow                                                                                                 
1      0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
2      0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
3      0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
4      0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
5      0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
6      3   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

Python-3.x相关问答推荐

如何在Python Matplotlib中在x轴上放置点

math. gcd背后的算法是什么,为什么它是更快的欧几里得算法?

如何获得给定列表中所有可能的元素组合?

如何绘制交叉验证的AUROC并找到最佳阈值?

tkinter treeview 如何在获取所选项目时将设置的对象作为对象返回

在不使用 split 函数的情况下从字符串中分割逗号(','),句号('.')和空格(' '),将字符串的单词附加到列表中

将 rgb numpy 图像转换为 rgb 列表和相应的索引值

如何在 20 秒后重复使用 Pillow 在现有图像上创建新图像?

!date 的命令无法从 jupyter notebook 运行

从 yahoo Finance python 一次下载多只股票

python中两个连续的yield语句如何工作?

Seaborn:注释线性回归方程

Python 3.9.8 使用 Black 并导入 `typed_ast.ast3` 失败

if 语句中冒号的语法错误

迭代器也是可迭代的吗?

为什么 2to3 将 mydict.keys() 更改为 list(mydict.keys())?

如何获得 BeautifulSoup 标签的所有直接子代?

Python:&= 运算符

Pyodbc:登录超时错误

Pylint 中的模块PyQt5.QtWidgets错误中没有名称QApplication