Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 计算每小时、每天的记录,并创建多索引数据帧作为输出_Python_Pandas - Fatal编程技术网

Python 计算每小时、每天的记录,并创建多索引数据帧作为输出

Python 计算每小时、每天的记录,并创建多索引数据帧作为输出,python,pandas,Python,Pandas,示例数据帧: process_id | app_path | start_time 所需的输出数据帧应基于开始时间列中的日期和时间值进行多索引,唯一日期作为第一级索引,一小时范围作为第二级索引。应计算每个时隙中的记录计数 def activity(self): # find unique dates from db file columns = self.df['start_time'].map(lambda x: x.date()).unique() result =

示例数据帧:

process_id | app_path | start_time

所需的输出数据帧应基于开始时间列中的日期和时间值进行多索引,唯一日期作为第一级索引,一小时范围作为第二级索引。应计算每个时隙中的记录计数

def activity(self):
    # find unique dates from db file
    columns = self.df['start_time'].map(lambda x: x.date()).unique()

    result = pandas.DataFrame(np.zeros((1,len(columns))), columns = columns)
    for i in range(len(self.df)):
        col = self.df.iloc[i]['start_time'].date()
        result[col][0] = result.get_value(0, col) + 1

    return result
我已经尝试了上面的代码,它给出了如下输出:

15-07-2014 16-7-2014 17-07-2014 18-07-2014
3217 2114 1027 3016

我还想按每小时统计记录

从一些样本数据开始提问会很有帮助。由于您没有这样做,我假设以下数据代表您的数据(看起来
app\u path
未被使用):

在Pandas数据帧中探索
groupby
方法可能会使您受益匪浅。使用groupby,您的上述示例将成为一个简单的单行程序:

df.groupby( [df.index.year, df.index.month, df.index.day] ).count()
按小时分组意味着只需将小时添加到组中:

df.groupby( [df.index.year, df.index.month, df.index.day, df.index.hour] ).count()

不要在Pandas中重新创建轮子,请使用提供的方法以获得更可读、更快速的代码

谢谢,但我想我必须把开始时间作为数据帧的索引。这给了我每列的计数,但我只想要一列表示计数。不,你不必使用索引。但这是时间序列数据的典型用例。如果开始时间在不同的列中,则使用该列名而不是索引。
df.groupby( [df.index.year, df.index.month, df.index.day, df.index.hour] ).count()