【问题标题】:Using groupby with expanding and a custom function使用带有扩展和自定义功能的 groupby
【发布时间】:2018-07-16 22:12:38
【问题描述】:

我有一个由 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 计算先前(即从数据顶部到该行)与其关联的唯一tracksId 集的长度:

       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

这与documentation一致

但是,当我尝试将此输出分配给新列时,它会引发错误:

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

我之前使用过这个工作流程,理想情况下,新列会毫无问题地放回原始 DateFrame 中(即拆分-应用-组合)。我怎样才能让它工作?

【问题讨论】:

    标签: python pandas lambda pandas-groupby split-apply-combine


    【解决方案1】:

    你需要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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-21
      • 2012-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      相关资源
      最近更新 更多