【问题标题】:Count the values for each aggregated data time计算每个聚合数据时间的值
【发布时间】:2020-06-28 00:40:44
【问题描述】:

我试图按小时聚合日期时间并计算值。

这是示例数据框:

   date_time
1/1/10 18:28:54 +0100 #format %d/%b/%Y %H:%M:%S %z
1/1/10 18:29:12 +0100
1/1/10 19:27:50 +0100
1/2/10 20:25:06 +0100

我需要这个:

date_time   count
1/1/10 18     2
1/1/10 19     1
1/2/10 20     1

这是我的代码:

times = pd.DatetimeIndex(df_3xx.date_time)
df_3xx = df_3xx.groupby([times.hour]).count()

我有什么:

ValueError: Array must be all same time zone
ValueError: Tz-aware datetime.datetime cannot be converted to datetime64 unless utc=True

非常感谢

【问题讨论】:

    标签: python-3.x pandas datetime


    【解决方案1】:

    我们可以试试:

    new_df = (df.assign(date_time = df['date_time'].astype(str).str[:9])
                .groupby('date_time').size().reset_index(name='count'))
    print(new_df)
    

    输出

       date_time  count
    0  1/1/10 18      2
    1  1/1/10 19      1
    2  1/2/10 20      1
    

    【讨论】:

    • 没有显示小时数,str[:9]真的靠谱吗?然后我可以使用 str[:13]
    • str: 9 显示到小时,str: 13 会显示到分钟,您可以在它显示的数据框中看到它,但如果在任何情况下您需要按分钟分组,您可以也使用 str [: 13]
    猜你喜欢
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多