使用groupby、expanding和自定义函数

7

我有一个包含truthIds和trackIds的数据帧:

truthId = ['A', 'A', 'B', 'B', 'C', 'C', 'A', 'C', 'B', 'A', 'A', 'C', 'C']
trackId = [1, 1, 2, 2, 3, 4, 5, 3, 2, 1, 5, 4, 6]
df1 = pd.DataFrame({'truthId': truthId, 'trackId': trackId})
    trackId truthId
0         1       A
1         1       A
2         2       B
3         2       B
4         3       C
5         4       C
6         5       A
7         3       C
8         2       B
9         1       A
10        5       A
11        4       C
12        6       C

我希望添加一列,计算每个唯一的truthId所关联的独特tracksIds集合的长度,这些tracksIds是之前(即从数据顶部到该行)与其关联的:

       truthId  trackId  unique_Ids
0        A        1           1
1        A        1           1
2        B        2           1
3        B        2           1
4        C        3           1
5        C        4           2
6        A        5           2
7        C        3           2
8        B        2           1
9        A        1           2
10       A        5           2
11       C        4           2
12       C        6           3

我离完成这个非常近了。我可以使用:

df.groupby('truthId').expanding().agg({'trackId': lambda x: len(set(x))})

这将产生以下输出:

                trackId
truthId            
A       0       1.0
        1       1.0
        6       2.0
        9       2.0
        10      2.0
B       2       1.0
        3       1.0
        8       1.0
C       4       1.0
        5       2.0
        7       2.0
        11      2.0
        12      3.0

这与文档一致。
然而,当我试图将此输出分配给新列时,它会抛出错误:
df['unique_Ids'] = df.groupby('truthId').expanding().agg({'trackId': lambda x: len(set(x))})

我以前用过这个工作流程,理想情况下新列会毫无问题地放回原始数据框中(即分割-应用-合并)。我该怎么让它工作?

1个回答

7

你需要使用 reset_index 方法。

df['Your']=(df.groupby('truthId').expanding().agg({'trackId': lambda x: len(set(x))})).reset_index(level=0,drop=True)
df
Out[1162]: 
    trackId truthId  Your
0         1       A   1.0
1         1       A   1.0
2         2       B   1.0
3         2       B   1.0
4         3       C   1.0
5         4       C   2.0
6         5       A   2.0
7         3       C   2.0
8         2       B   1.0
9         1       A   2.0
10        5       A   2.0
11        4       C   2.0
12        6       C   3.0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接