Christian Frei
Christian Frei

Reputation: 481

Pivottable in Pandas

I have an Dataframe like this:

Col1 Col2
A    Foo1
A    Foo3
B    Foo1
B    Foo3
B    Foo4
C    Foo1
D    Foo3
D    Foo4

And I need an output like this:

       Foo1     Foo3      Foo4
A    1             1            0
B    1             1            1
C    1             0            0
D    0             1            1

What is the simplest way in pandas to reach this, without using foreach loops in python.

Upvotes: 1

Views: 54

Answers (1)

jezrael
jezrael

Reputation: 862511

The simpliest is crosstab:

df1 = pd.crosstab(df['Col1'], df['Col2'])

Another solution is GroupBy.size with unstack:

df1 = df.groupby(['Col1','Col2']).size().unstack(fill_value=0)

print (df1)
Col2  Foo1  Foo3  Foo4
Col1                  
A        1     1     0
B        1     1     1
C        1     0     0
D        0     1     1

Upvotes: 1

Related Questions