Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge Pandas DataFrame rows into a string in one column

Tags:

python

pandas

Given this DataFrame

       r3  value
r1 r2           
1  2    3      1
   2    4      1
   3    2      1
   3    4      1
   4    2      1
   4    3      1
2  1    3      1
   1    4      1
   3    1      1
   3    4      1
   4    1      1
   4    3      1

...what's the best way to do this?

        r3     value
r1 r2           
1  2    3,4    2
   3    2,4    2
   4    2,3    2
2  1    3,4    2
   3    1,4    2
   4    1,3    2

Basically, I'm trying to condense the r3 column into a comma delimited string. The value column can be achieved a different way later on if necessary, or if it can be done through this whole process, even better.

like image 782
TravisVOX Avatar asked Aug 07 '14 15:08

TravisVOX


1 Answers

You could use the agg function after grouping the dataframe. if df is your dataframe use this...

strJoin = lambda x:",".join(x.astype(str))     
df.groupby(level=[0,1]).agg({"r3":strJoin,"value":np.sum})
like image 188
ZJS Avatar answered Oct 12 '22 08:10

ZJS