0

This is my DataFrame:

`df = pd.DataFrame([['A', 1], ['A', 2], ['A', 3], ['B', 1], ['B', 2]],
                   columns=['Key', 'Value'])`
Key Value
0 A 1
1 A 2
2 A 3
3 B 1
4 B 2

When I am using...

`df.groupby(['Key']).count()`

...the output is:

Key Value
A 3
B 2

But I want my output to be:

| |Key |Value |Count| |:---|:-----:|:-----:|----:| |0 |A |1 |3 | |1 |A |2 |3 | |2 |A |3 |3 | |3 |B |1 |2 | |4 |B |2 |2 |

I didn't find a solution in the forum, thanks for the help

buhtz
  • 10,774
  • 18
  • 76
  • 149
Guyblublu
  • 26
  • 3

1 Answers1

2

you probably want transform which preserves the original shape:

df['Count'] = df.groupby(['Key']).transform("count")

  Key  Value  Count
0   A      1      3
1   A      2      3
2   A      3      3
3   B      1      2
4   B      2      2
anon01
  • 10,618
  • 8
  • 35
  • 58