python - 计算由唯一来源发布的两条新闻之间的平均每日时间量

标签 python pandas datetime

我有一个 pandas 数据框(我有一个简化的表格,示例中显示了一个日期),我想计算由唯一来源发布的两条新闻之间的平均每日时间量

输入

source          date           time     
Investing.com   2017-05-11     08:00:00     
Investing.com   2017-05-11     12:00:00
Investing.com   2017-05-11     16:00:00 
yahoo.com       2017-05-11     09:00:00 
yahoo.com       2017-05-11     12:00:00
yahoo.com       2017-05-11     15:00:00
yahoo.com       2017-05-12     06:00:00 
yahoo.com       2017-05-12     12:00:00
yahoo.com       2017-05-12     18:00:00  

所需输出

source          date           Average_Daily_time   
Investing.com   2017-05-11     04:00:00      
yahoo.com       2017-05-11     03:00:00
yahoo.com       2017-05-12     06:00:00 

我的尝试

我将日期时间合并到一个时间戳中,并将其称为日期时间

df.sort_values('datetime').groupby('source')['datetime'].apply(lambda x: x.diff().dt.seconds.mean()/60)

问题

它计算所有日期组合的平均时间,而不是单独日期的平均时间。如何显示不同日期的平均时间?

最佳答案

转换time列至timedelta ,然后group数据框 sourcedate和聚合time使用 lambda 函数计算 meandiff行与行之间

df['time'] = pd.to_timedelta(df['time'])
(
    df.groupby(['source', 'date'])['time']
      .agg(lambda d: d.diff().mean()).reset_index(name='avg')
)

          source        date             avg
0  Investing.com  2017-05-11 0 days 04:00:00
1      yahoo.com  2017-05-11 0 days 03:00:00
2      yahoo.com  2017-05-12 0 days 06:00:00

关于python - 计算由唯一来源发布的两条新闻之间的平均每日时间量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72713113/

相关文章:

Python - 无法从 __future__ 导入 with_statement

python - Pandas 中带有时区列的时间戳

python - 取消堆叠 "multi-indexed"列|在 Pandas 中

将时间从 UTC 转换为指定的时区时出现 .NET PCL 异常

mysql - 如何从 UTC 时间获取 MySQL 中的 Unix 时间戳?

iphone - Sqlite查询,将日期时间字段与当前日期时间进行比较

python - Kivy ScrollView - 不滚动

python - 如何获取仅属于我们在左连接中引入的右表的列名

python - 如果 'W' 在 'X' 中,则将 'Y' 附加到 'Z'

python - 如何使用 python 和 ssh 遍历交换机的所有端口并一一禁用它们?