总结每天大熊猫的出现次数

新手上路,请多包涵

我在熊猫数据框中有一个这样的数据集:

                                   score
timestamp
2013-06-29 00:52:28+00:00        -0.420070
2013-06-29 00:51:53+00:00        -0.445720
2013-06-28 16:40:43+00:00         0.508161
2013-06-28 15:10:30+00:00         0.921474
2013-06-28 15:10:17+00:00         0.876710

我需要计算发生的测量次数,所以我正在寻找这样的东西:

                                     count
   timestamp
   2013-06-29                       2
   2013-06-28                       3

我不关心情绪栏,我想要每天发生的次数。

原文由 Mahdi Yusuf 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 350
2 个回答

如果您的 timestamp 索引是 DatetimeIndex

 import io
import pandas as pd
content = '''\
timestamp  score
2013-06-29 00:52:28+00:00        -0.420070
2013-06-29 00:51:53+00:00        -0.445720
2013-06-28 16:40:43+00:00         0.508161
2013-06-28 15:10:30+00:00         0.921474
2013-06-28 15:10:17+00:00         0.876710
'''

df = pd.read_table(io.BytesIO(content), sep='\s{2,}', parse_dates=[0], index_col=[0])

print(df)

所以 df 看起来像这样:

                         score
timestamp
2013-06-29 00:52:28 -0.420070
2013-06-29 00:51:53 -0.445720
2013-06-28 16:40:43  0.508161
2013-06-28 15:10:30  0.921474
2013-06-28 15:10:17  0.876710

print(df.index)
# <class 'pandas.tseries.index.DatetimeIndex'>

您可以使用:

 print(df.groupby(df.index.date).count())

哪个产量

            score
2013-06-28      3
2013-06-29      2


请注意 parse_dates 参数的重要性。没有它,索引将只是一个 pandas.core.index.Index 对象。在这种情况下,您不能使用 df.index.date

所以答案取决于 type(df.index) ,你没有显示……

原文由 unutbu 发布,翻译遵循 CC BY-SA 3.0 许可协议

否则,使用 resample 函数。

 In [419]: df
Out[419]:
timestamp
2013-06-29 00:52:28   -0.420070
2013-06-29 00:51:53   -0.445720
2013-06-28 16:40:43    0.508161
2013-06-28 15:10:30    0.921474
2013-06-28 15:10:17    0.876710
Name: score, dtype: float64

In [420]: df.resample('D', how={'score':'count'})

Out[420]:
2013-06-28    3
2013-06-29    2
dtype: int64

更新:熊猫 0.18+

正如@jbochi 指出的那样,现在不推荐使用 how 重新采样。改用:

 df.resample('D').apply({'score':'count'})

原文由 gowithefloww 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题