Merge Pandas rows of a DataFrame into a row in one column

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 is 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 a column r3into a comma-separated string. The column valuecan be reached in another way later, if necessary, or if it can be done through this whole process, even better.

+4
source share
1 answer

You can use the agg function after grouping the data frame. if dfis your dataframe, use this ...

strJoin = lambda x:",".join(x.astype(str))     
df.groupby(level=[0,1]).agg({"r3":strJoin,"value":np.sum})
+3
source

All Articles