0

I have a dataframe with 2 columns; id and item. id is the id and item is the value of the id. 1. I wish to first groupby my dataframe and then find the number of size of each id as below. 2. Then after getting the count, i wish to append the value at the back of the count by using .merge function.

a = pd.DataFrame({'id':[1,1,1,1,2,2,2,3],
                 'item':['test1', 'test2', 'test3', 'test4', 'value1', 'value2', 'value3', 'total1']})
a.groupby('id').size().reset_index(name='count')

result:

    id  count
0   1   4
1   2   3
2   3   1

expected

    id  item   count
0   1   test1   4
1   1   test2   4
2   1   test3   4
3   1   test4   4
4   2   value1   3
5   2   value2   3
6   2   value3   3
7   3   total1   1
Anony
  • 109
  • 1
  • 9
  • use transform here: `a['count']=a.groupby('id')['item'].transform('size')` – anky Mar 17 '20 at 15:41
  • is there a way to use my method according to sequence then apply .merge? I wish to use that way instead of changing the sequence – Anony Mar 17 '20 at 15:42
  • use `a = a.merge(a.groupby('id').size().reset_index(name='count'),on='id')` – anky Mar 17 '20 at 15:47

0 Answers0