[英]Using Pandas, how to group a JSON data by day and count the occurrences?
I know this question looks a bit absurd, but I've been searching for its solution all day long today and got nothing. 我知道这个问题看起来有点荒谬,但我今天一整天都在寻找它的解决方案而一无所获。
I have a JSON object 我有一个JSON对象
times = [1554278809, 1554276258, 1554274173, 1554270457] /* four occurrences in April 3 */
I need to group it by day and count the occurrence and get a result like: 我需要按天分组并计算事件并得到如下结果:
result = [{'2019-04-01': 0, '2019-04-02': 0, '2019-04-03': 4}]
So far, I've tried this (which, as expected, doesn't work): 到目前为止,我已经尝试过这个(正如预期的那样,它不起作用):
times = [str(datetime.fromtimestamp(x)) for x in times]
df = pd.DataFrame(times)
print(df.groupby(df.index.date).count())
Create Series
with to_datetime
convert unix time and then convert it to strings by Series.dt.strftime
: 使用to_datetime
创建Series
转换unix时间,然后通过Series.dt.strftime
将其转换为字符串:
times = [1554278809, 1554276258, 1554274173, 1554270457]
s = pd.Series(pd.to_datetime(times, unit='s'))
print (s)
0 2019-04-03 08:06:49
1 2019-04-03 07:24:18
2 2019-04-03 06:49:33
3 2019-04-03 05:47:37
dtype: datetime64[ns]
print(s.groupby(s.dt.strftime('%Y-%m-%d')).count().to_dict())
{'2019-04-03': 4}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.