0

I have a df which follows this structure:

                value           value_1

index_1         abc             300
                abc             235
                abc             359
                abc             167
index_2         def             64
                def             641
index_3         ghi             12
index_4         jkl             1
                jkl             10

I am trying to add another column count which is the count of value per each index so that the df would look like this:

                value           value_1         count

index_1         abc             300             4
                abc             235             4
                abc             359             4
                abc             167             4
index_2         def             64              2
                def             641             2
index_3         ghi             12              1
index_4         jkl             1               2
                jkl             10              2

I tried:

df.groupby(level=0).count()['value']

Which returns the series of the counts I, but when I add it to df it all nan

df['count'] = df.groupby(level=0).count()['value']
                value           value_1         count

index_1         abc             300             nan
                abc             235             nan
                abc             359             nan
                abc             167             nan
index_2         def             64              nan
                def             641             nan
index_3         ghi             12              nan
index_4         jkl             1               nan
                jkl             10              nan

Where is my mistake?

Jonas Palačionis
  • 4,591
  • 4
  • 22
  • 55

0 Answers0