我有一个数据框,其列 created_at
和 entities
如下所示
created_at entities
2017-10-29 23:06:28 {'hashtags': [{'text': 'OPEC', 'indices': [0, ...
2017-10-29 22:28:20 {'hashtags': [{'text': 'Iraq', 'indices': [21,...
2017-10-29 20:01:37 {'hashtags': [{'text': 'oil', 'indices': [58, ...
2017-10-29 20:00:14 {'hashtags': [{'text': 'oil', 'indices': [38, ...
2017-10-27 08:44:30 {'hashtags': [{'text': 'Iran', 'indices': [19,...
2017-10-27 08:44:10 {'hashtags': [{'text': 'Oil', 'indices': [17, ...
2017-10-27 08:43:13 {'hashtags': [{'text': 'Oil', 'indices': [0, 4...
2017-10-27 08:43:00 {'hashtags': [{'text': 'Iran', 'indices': [19,.
我想计算每一天的实体数量 . 基本上我想收到类似的东西
created_at number_of_entities
2017-10-29 4
2017-10-27 4
怎么做?我有 pandas 0.23.4
5 回答
您可以使用floor或date删除时间,然后使用value_counts进行计数,将rename_axis和reset_index用于2列
DataFrame
:要么:
如果想避免在
value_counts
传递参数sort=False
中进行默认排序:使用
groupby.size
特定
同
你可以发出:
jezrael在评论中提出了一种没有
PeriodIndex
构造函数的更好的方法:通过一些额外的重命名来匹配您的输出,它开始看起来像jezrael的解决方案 . ;)
或者,您可以将索引设置为日期,然后
resample
:...如果需要转换为您的确切输出:
更多上下文:
resample
对于任意时间间隔特别有用,例如"five minutes" . 以下示例直接来自Wes McKinney的书"Python for Data Analysis" .给你数据:
您可以按如下方式使用groupby(..).count()来获得您想要的内容:
Notice that:
如果
created_at
列已经采用日期时间格式,则只需使用以下内容:您可以使用
df.groupby(df.created_at.dt.day)
按天分组 .至于计算计数的函数,为此我们需要一个完整的行,你的数据结构看起来很奇怪 .