Python 熊猫:重新采样后计数唯一值

Python 熊猫:重新采样后计数唯一值,python,pandas,Python,Pandas,我刚刚开始使用Pandas,并尝试进行组合:按日期对数据进行分组,并计算每组中的唯一值 以下是我的数据: User, Type Datetime 2014-04-15 11:00:00, A, New 2014-04-15 12:00:00, B, Returning 2014-04-15 13:00:00, C, New 2014-04-20 14:00:00, D, New 2014-04-20 15:00:00, B, Returning 2014-04

我刚刚开始使用Pandas,并尝试进行组合:按日期对数据进行分组,并计算每组中的唯一值

以下是我的数据:

                  User, Type
Datetime
2014-04-15 11:00:00, A, New
2014-04-15 12:00:00, B, Returning
2014-04-15 13:00:00, C, New
2014-04-20 14:00:00, D, New
2014-04-20 15:00:00, B, Returning
2014-04-20 16:00:00, B, Returning
2014-04-20 17:00:00, D, Returning
下面是我想做的:将datetime索引重新采样到当天(我可以做到),并计算每天的唯一用户数。 我对“类型”栏还不感兴趣

Day, Unique Users
2014-04-15, 3
2014-04-20, 2

我正在尝试
df.user.resample('D',how='count')。unique
,但它似乎没有给我正确的答案。

您不需要进行重采样就可以获得问题中所需的输出。我想您只需在约会时使用
groupby

print df.groupby(df.index.date)['User'].nunique()

2014-04-15    3
2014-04-20    2
dtype: int64
然后,如果您愿意,您可以在计算唯一用户数后重新采样以填补时间序列空白:

cnt = df.groupby(df.index.date)['User'].nunique()
cnt.index = cnt.index.to_datetime()
print cnt.resample('D')

2014-04-15     3
2014-04-16   NaN
2014-04-17   NaN
2014-04-18   NaN
2014-04-19   NaN
2014-04-20     2
Freq: D, dtype: float64

我遇到了同样的问题。卡尔·D的答案适用于某种重新编制索引的方法——例如,在日期上。但是,如果您希望索引是

Jan 2014
Feb 2014
March 2014
然后把它画成时间序列

以下是我所做的:

df.user.resample('M',lambda x: x.nunique())

我遇到了同样的问题。重新取样为我和努尼克工作。使用重采样的好方法是,它可以非常简单地将采样率更改为小时或分钟,并将时间戳保留为索引

df.user.resample('D').nunique()

我不得不使用
打印df.groupby(df.index.date)['User'].apply(lambda x:x.nunique())
,但这很有效。谢谢