Patthebug
Patthebug

Reputation: 4787

Dataerror using pivot in pandas

I'm using the following command to pivot a bunch of rows:

df[df.branch=='ALG'].reset_index().pivot_table(index='branch', columns='monyear', values='conceptname')

The column conceptname is a string column and therefore I get the following error:

DataError: No numeric types to aggregate

How do I get pandas to ignore this? I don't really want to aggregate anything, I just want to reshape my data in a columnar format.

Here's my input data:

branch    monyear    conceptname
A          Jul         text1
A          Jul         text2
A          Aug         text3
A          Aug         text4
B          Jul         text5
B          Jul         text6
B          Aug         text7
B          Aug         text8

Desired output:

branch    Jul    Aug
A        text1  text3
A        text2  text4
B        text5  text7
B        text6  text8

A and B can be thought of as different branches selling stuff in different months (Jul and Aug). I'd like to list the stuff sold by these branches in different months.

Any help would be appreciated. TIA.

Upvotes: 0

Views: 57

Answers (1)

piRSquared
piRSquared

Reputation: 294348

Try:

df_ = df.set_index(['branch']).groupby('monyear').apply(lambda x: x.T).T

df_ = df_.xs('conceptname', axis=1, level=1)

print df_

monyear    Aug    Jul
branch               
A        text3  text1
A        text4  text2

Upvotes: 3

Related Questions