我在pandas数据框中有一个类似这样的数据集:
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我不关心情感栏,我想要的是每天发生的次数。
发布于 2013-07-18 01:27:32
如果您的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),您还没有展示它。
发布于 2015-04-09 23:24:57
否则,使用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更新:使用pandas 0.18+
正如@jbochi指出的那样,使用how重新采样现在已被弃用。请改用:
df.resample('D').apply({'score':'count'})发布于 2013-07-18 01:21:48
In [145]: df
Out[145]:
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 [160]: df.groupby(lambda x: x.date).count()
Out[160]:
2013-06-28 3
2013-06-29 2
dtype: int64https://stackoverflow.com/questions/17706109
复制相似问题