Python 每个日期唯一ID的累积计数
假设我有以下DF:Python 每个日期唯一ID的累积计数,python,pandas,numpy,Python,Pandas,Numpy,假设我有以下DF: Date ID 2019-06-01 A 2019-06-01 B 2019-06-01 B 2019-06-02 A 2019-06-02 C 2019-06-03 C 2019-06-03 A 获取每个日期唯一ID的累积计数的最具python风格的方法是什么: Date ID 2019-06-01 2 2019-06-02 3 2019-06-03 3 我可以按
Date ID
2019-06-01 A
2019-06-01 B
2019-06-01 B
2019-06-02 A
2019-06-02 C
2019-06-03 C
2019-06-03 A
获取每个日期唯一ID的累积计数的最具python风格的方法是什么:
Date ID
2019-06-01 2
2019-06-02 3
2019-06-03 3
我可以按日期使用for循环,并使用np.isin
,但这在性能方面太糟糕了
谢谢让我们做吧
s = df.groupby('Date')['ID'].agg(list).cumsum()
s = s.map(lambda x : len(set(x))).reset_index()
s
Date ID
0 2019-06-01 2
1 2019-06-02 3
2 2019-06-03 3
让我们做吧
s = df.groupby('Date')['ID'].agg(list).cumsum()
s = s.map(lambda x : len(set(x))).reset_index()
s
Date ID
0 2019-06-01 2
1 2019-06-02 3
2 2019-06-03 3
使用cumsum()尝试groupby().nunique
:
输出:
2019-06-01 2.0
2019-06-02 3.0
2019-06-03 3.0
Freq: D, Name: ID, dtype: float64
使用cumsum()尝试groupby().nunique
:
输出:
2019-06-01 2.0
2019-06-02 3.0
2019-06-03 3.0
Freq: D, Name: ID, dtype: float64
不知怎么的,这给了我错误的结果。例如,在我的例子中:A=第一天uniques:size 40941。B=第二天单件:尺寸28262。C=B[~np.isin(B,A)]大小12114,然后C+A=53055,代码给了我第一天的唯一性:3519和第二天的唯一性:5486不知何故,这给了我错误的结果。例如,在我的例子中:A=第一天uniques:size 40941。B=第二天单件:尺寸28262。C=B[~np.isin(B,A)]大小为12114,然后C+A=53055,代码给了我第一天的唯一性:3519和第二天:5486