Python Pandas, collection of multiple columns from one

I am new to pandas and I have a DataFrame of this type:

    name    value
0   alpha   a
1   beta    b
2   gamma   c
3   alpha   a
4   beta    b
5   beta    a
6   gamma   a
7   alpha   c

      

which I would like to turn into one of these types:

    name    a   b   c
0   alpha   2   0   1
1   beta    1   2   0
2   gamma   1   0   1

      

That is, I would like to group "name" and "value", then count them and create a column for each value "value" that I find.

+3


source to share


1 answer


It's just cross-tabulation:

In [78]:

print pd.crosstab(df.name, df.value)
value  a  b  c
name          
alpha  2  0  1
beta   1  2  0
gamma  1  0  1

      

If you are using groupby

:



In [90]:

print df.groupby(['name', 'value']).agg(len).unstack().fillna(0)
value  a  b  c
name          
alpha  2  0  1
beta   1  2  0
gamma  1  0  1

      

The latter could be faster:

In [92]:

%timeit df.groupby(['name', 'value']).agg(len).unstack().fillna(0)
100 loops, best of 3: 3.26 ms per loop
In [93]:

%timeit pd.crosstab(df.name, df.value)
100 loops, best of 3: 7.5 ms per loop

      

+5


source







All Articles