4

I have a requirement where in I am trying to count the values and Put them in the pivot table.

This is my dataframe,

  Cola        Colb          
 Apple    Rippened 
Orange    Rippened
 Apple  UnRippened
 Mango  UnRippened

I want the Output to be like this,

        Rippened  UnRippened
Apple          1           1
Mango          0           1
Orange         1           0

Kindly share your thoughts.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • Duplicate of https://stackoverflow.com/questions/30679467/pivot-tables-or-group-by-for-pandas/30679543#30679543 – Zero Sep 20 '17 at 03:47

3 Answers3

11

I love this question....

Option 1

pd.get_dummies(df.Cola).T.dot(pd.get_dummies(df.Colb))

        Rippened  UnRippened
Apple          1           1
Mango          0           1
Orange         1           0

Option 2

i, r = pd.factorize(df.Cola.values)
j, c = pd.factorize(df.Colb.values)
n, m = r.size, c.size
b = np.bincount(i * m + j, minlength=n * m).reshape(n, m)

pd.DataFrame(b, r, c)

        Rippened  UnRippened
Apple          1           1
Orange         1           0
Mango          0           1

Option 3

df.groupby(['Cola', 'Colb']).size().unstack(fill_value=0)

Colb    Rippened  UnRippened
Cola                        
Apple          1           1
Mango          0           1
Orange         1           0

Option 4

df.groupby('Cola').Colb.value_counts().unstack(fill_value=0)

Colb    Rippened  UnRippened
Cola                        
Apple          1           1
Mango          0           1
Orange         1           0
piRSquared
  • 285,575
  • 57
  • 475
  • 624
8

Using my favourite: pd.crosstab

df = pd.crosstab(df.Cola, df.Colb)
print(df)

Colb    Rippened  UnRippened
Cola                        
Apple          1           1
Mango          0           1
Orange         1           0
cs95
  • 379,657
  • 97
  • 704
  • 746
7

IIUC:

In [178]: d.pivot_table(index='Cola', columns='Colb', aggfunc='size', fill_value=0)
Out[178]:
Colb    Rippened  UnRippened
Cola
Apple          1           1
Mango          0           1
Orange         1           0
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419