gpt4 book ai didi

python - Pandas :与 TimeGrouper 分组

转载 作者:太空狗 更新时间:2023-10-30 02:17:57 33 4
gpt4 key购买 nike

我有数据

i,ID,url,used_at,active_seconds,domain,search_term  
322015,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/antoninaribina,2015-12-31 09:16:05,35,vk.com,None
838267,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/feed,2015-12-31 09:16:38,54,vk.com,None
838271,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/feed?section=photos,2015-12-31 09:17:32,34,vk.com,None
322026,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/feed?section=photos&z=photo143297356_397216312%2Ffeed1_143297356_1451504298,2015-12-31 09:18:06,4,vk.com,None
838275,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/feed?section=photos,2015-12-31 09:18:10,4,vk.com,None
322028,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/feed?section=comments,2015-12-31 09:18:14,8,vk.com,None
322029,0120bc30e78ba5582617a9f3d6dfd8ca,megarand.ru/contest/121070,2015-12-31 09:18:22,16,megarand.ru,None
1870917,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/feed?section=comments,2015-12-31 09:18:38,6,vk.com,None
1354612,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/antoninaribina,2015-12-31 09:18:44,56,vk.com,None

我需要按 ID 分组,然后按 used_at 分组,其中 2 个字符串之间的差异超过 500 秒。我试试

df.groupby([df['ID', 'used_at'],pd.TimeGrouper(freq='5Min')])

但它返回 KeyError: ('ID', 'used_at')

最佳答案

您需要的 IIUC:

print (df.groupby('ID')['used_at'].diff().dt.seconds)
0 NaN
1 33.0
2 54.0
3 34.0
4 4.0
5 4.0
6 8.0
7 16.0
8 6.0
Name: used_at, dtype: float64

如果你想使用 TimeGrouper,你应该首先设置一个 Datetimeindex 然后你可以使用任何聚合函数 - 例如总和:

df['used_at'] = pd.to_datetime(df.used_at)
df.set_index('used_at', inplace=True)
print (df.groupby([df['ID'],pd.TimeGrouper(freq='5Min')]).sum())

另一种方法是将列 used_at 复制到 index:

df['used_at'] = pd.to_datetime(df.used_at)
df.set_index(df['used_at'], inplace=True)
print (df.groupby([df['ID'], df['used_at'],pd.TimeGrouper(freq='5Min')]).sum())

关于python - Pandas :与 TimeGrouper 分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38269802/

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