Pandas Dataframe: how to add column with number of occurrences in other column

前端 未结 3 1707
梦毁少年i
梦毁少年i 2020-12-17 00:17

I have to following df:

Col1    Col2
test    Something
test2   Something
test3   Something
test    Something
test2   Something
test5   Something
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-17 00:50

    You can also use GroupBy + transform with size:

    df['Occur'] = df.groupby('Col1')['Col1'].transform('size')
    
    print(df)
    
        Col1       Col2  Occur
    0   test  Something      2
    1  test2  Something      2
    2  test3  Something      1
    3   test  Something      2
    4  test2  Something      2
    5  test5  Something      1
    

提交回复
热议问题