python - 如何在 pandas 数据框上计算一天的小时数

标签 python pandas dataframe timestamp

我做了多天的观察,一个客户可以再多几天观察,这是我的数据,

customer_id   value    timestamp
1             1000     2018-05-28 03:40:00.000
1             1450     2018-05-28 04:40:01.000
1             1040     2018-05-28 05:40:00.000
1             1500     2018-05-29 02:40:00.000
1             1090     2018-05-29 04:40:00.000
3             1060     2018-05-18 03:40:00.000
3             1040     2018-05-18 05:40:00.000
3             1520     2018-05-19 03:40:00.000
3             1490     2018-05-19 04:40:00.000

基于上一个问题How do I building dt.hour in 2 days第一个出现的客户是 2018-05-28 03:40:00.000 并标记为 Day1 - 3,但出于其他目的应该是 Day1 - 0,所以输出为

customer_id   value    timestamp                hour
1             1000     2018-05-28 03:40:00.000  Day1 - 0
1             1450     2018-05-28 04:40:01.000  Day1 - 1
1             1040     2018-05-28 05:40:00.000  Day1 - 2
1             1500     2018-05-29 02:40:00.000  Day1 - 23
1             1090     2018-05-29 04:40:00.000  Day2 - 1
3             1060     2018-05-18 03:40:00.000  Day1 - 0
3             1040     2018-05-18 05:40:00.000  Day1 - 2
3             1520     2018-05-19 03:40:00.000  Day2 - 0
3             1490     2018-05-19 04:40:00.000  Day2 - 1

最佳答案

我认为需要添加所有缺失的时间才能正确 cumcount :

#floor to hours
df['timestamp'] = df['timestamp'].dt.floor('h')
#add missing hours per group
df = df.set_index('timestamp').groupby('customer_id').apply(lambda x: x.asfreq('h'))
#cumulative count per group
df['hour'] = df.groupby(level=0).cumcount() 
df= df.dropna(subset=['customer_id']).drop('customer_id', 1).reset_index()

df['hour'] = ('Day' + (df['hour'] // 24).add(1).astype(str) +
              ' - ' + (df['hour'] % 24).astype(str))
print (df) 
   customer_id           timestamp   value       hour
0            1 2018-05-28 03:00:00  1000.0   Day1 - 0
1            1 2018-05-28 04:00:00  1450.0   Day1 - 1
2            1 2018-05-28 05:00:00  1040.0   Day1 - 2
3            1 2018-05-29 02:00:00  1500.0  Day1 - 23
4            1 2018-05-29 04:00:00  1090.0   Day2 - 1
5            3 2018-05-18 03:00:00  1060.0   Day1 - 0
6            3 2018-05-18 05:00:00  1040.0   Day1 - 2
7            3 2018-05-19 03:00:00  1520.0   Day2 - 0
8            3 2018-05-19 04:00:00  1490.0   Day2 - 1

关于python - 如何在 pandas 数据框上计算一天的小时数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51078117/

相关文章:

python - 优化Python字典中的插入操作

python - Python 的 difflib.HtmlDiff 的语义标记

python - bool 索引的优雅方法,列表中具有可变/动态数量的值

pandas - Pandas 中两个时间戳之间的差异

python - 如何对pandas数据框中的复杂条件求和

python - Pandas 通过多个键连接数据框

Python 请求开启多个实例

python - Numpy - 使用索引数组索引数组的最后一个维度

r - 在R中将数据从一个数据帧扩展到另一个数据帧的多行

python - 根据自定义范围离散化 Pandas 列