【问题标题】:how do I classify or regroup dataset based on time variation in python如何根据python中的时间变化对数据集进行分类或重组
【发布时间】:2020-01-31 23:43:52
【问题描述】:

我需要为每小时不同时间之间的值分配数字。然后如何向其中添加一个新列,我可以在其中指定每个单元格按小时分组。比如00:00:00到00:59:59之间的所有交易都填1,01:00:00到01:59:59之间的交易都填2,以此类推直到23:00 :00 到 23:59:59 填满 24

Time_duration = df['period']

print (Time_duration)
0        23:59:56
1        23:59:56
2        23:59:55
3        23:59:53
4        23:59:52
           ...
74187    00:00:18
74188    00:00:09
74189    00:00:08
74190    00:00:03
74191    00:00:02 ```


# this is the result I desire.... How can I then add a new column to this where I can specify each cell to be grouped hourly. for instance, all the transactions within 00:00:00 to 00:59:59 to be filled with 1, transactions within 01:00:00 to 01:59:59 to be filled with 2, and so on till 23:00:00 to 23:59:59 to be filled with 24.

0        23:59:56        24
1        23:59:56        24
2        23:59:55        24
3        23:59:53        24
4        23:59:52        24
           ...
74187    00:00:18         1
74188    00:00:09         1
74189    00:00:08         1
74190    00:00:03         1
74191    00:00:02         1


【问题讨论】:

    标签: python python-3.x pandas numpy datetime


    【解决方案1】:
    df.sort_values(by=["period"])
    timeStamp_list = (pd.to_datetime(list(df['period'])))
    df['Hour'] =timeStamp_list.hour
    

    试试这个代码,这对我有用。

    【讨论】:

      【解决方案2】:

      您可以使用regular expressionsstr.extract

      import pandas as pd
      pattern= r'^(\d{1,2}):' #capture the digits of the hour
      df['hour']=df['period'].str.extract(pattern).astype('int') + 1 # cast it as int so that you can add 1
      

      【讨论】:

        猜你喜欢
        • 2020-06-18
        • 2013-12-05
        • 2021-12-03
        • 2017-11-24
        • 1970-01-01
        • 1970-01-01
        • 2021-03-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多