gpt4 book ai didi

python-3.x - Pandas:如何使用开始和结束时间戳分析数据?

转载 作者:行者123 更新时间:2023-12-05 06:38:55 25 4
gpt4 key购买 nike

我必须分析在给定时间段内使用应用程序的用户的事件,时间段是开始和结束时间戳。我尝试使用条形图,但我不知道如何在间隔中包含小时数。例如:uid=2 的用户使用位于 [18, 19, 20, 21] 的应用程序

我的数据框是这样的:

uid           sex          start                 end
1 0 2000-01-28 16:47:00 2000-01-28 17:47:00
2 1 2000-01-28 18:07:00 2000-01-28 21:47:00
3 1 2000-01-28 18:47:00 2000-01-28 20:17:00
4 0 2000-01-28 08:00:00 2000-01-28 10:00:00
5 1 2000-01-28 02:05:00 2000-01-28 02:30:00
6 0 2000-01-28 15:10:00 2000-01-28 18:04:00
7 0 2000-01-28 01:50:00 2000-01-28 03:00:00


df['hour_s'] = pd.to_datetime(df['start']).apply(lambda x: x.hour)
df['hour_e'] = pd.to_datetime(df['end']).apply(lambda x: x.hour)

uid sex start end hour_s hour_e
1 0 2000-01-28 16:47:00 2000-01-28 17:47:00 16 17
2 1 2000-01-28 18:07:00 2000-01-28 21:47:00 18 21
3 1 2000-01-28 18:47:00 2000-01-28 20:17:00 18 20
4 0 2000-01-28 08:00:00 2000-01-28 10:00:00 08 10
5 1 2000-01-28 02:05:00 2000-01-28 02:30:00 02 02
6 0 2000-01-28 15:10:00 2000-01-28 18:04:00 15 18
7 0 2000-01-28 01:50:00 2000-01-28 03:00:00 01 03

我必须找到特定时间内的用户数量

最佳答案

我不确定您是否在寻找甘特图。如果是这样,@Vinícius Aguiar 的提示在评论中。

从你的最后一行

I have to find number of users in a specifc hours

您似乎需要一个直方图来显示按一天中的小时旋转的用户数量(频率)。如果是这种情况,您可以执行以下操作:

#! /usr/bin/python3

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# Read the data
df=pd.read_csv("data.csv")

# Get all hours per user (per observation)
def sum_hours(obs):
return(list(range(obs['hour_s'],obs['hour_e']+1,1)))

# Get all existing activity hours (No matter which user)
Hours2D=list(df.apply(sum_hours,axis=1))
# Get all existing hours
HoursFlat=[hour for sublist in Hours2D for hour in sublist]

plt.hist(HoursFlat,rwidth=0.5,range=(0,24))
plt.xticks(np.arange(0,24, 1.0))
plt.xlabel('Hour of day')
plt.ylabel('Users')
plt.show()

其中 data.csv 是您提供的示例:

uid, sex,start,end,hour_s,hour_e
1,0,2000-01-28 16:47:00,2000-01-28 17:47:00,16,17
2,1,2000-01-28 18:07:00,2000-01-28 21:47:00,18,21
3,1,2000-01-28 18:47:00,2000-01-28 20:17:00,18,20
4,0,2000-01-28 08:00:00,2000-01-28 10:00:00,08,10
5,1,2000-01-28 02:05:00,2000-01-28 02:30:00,02,02
6,0,2000-01-28 15:10:00,2000-01-28 18:04:00,15,18
7,0,2000-01-28 01:50:00,2000-01-28 03:00:00,01,03

你应该得到下图: Data pivoted showing user amounts by hour

关于python-3.x - Pandas:如何使用开始和结束时间戳分析数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45363409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com