0

I have a dataframe, A, which looks like this:

col1    col2
 1       low
 1       low
 1       high
 2       low
 2       high

Now, I want to group this dataframe on col1, while getting the count of every element in col2 in a separate column. So, the resulting dataframe, B, should look like this:

 col1     low    high
  1        2       1
  2        1       1

I am trying to do this by using group_by, however this is not working. Anyone knows how to do this?

bml
  • 115
  • 7

1 Answers1

0

Here's my try using value_counts -> reset_index -> pivot -> apply (dropna) -> astype(int)

df2.value_counts().reset_index().pivot(columns='col2',values=0).apply(lambda x: pd.Series(x.dropna().values)).astype(int)
Wasif
  • 14,755
  • 3
  • 14
  • 34