sequence_hard
sequence_hard

Reputation: 5385

How to put values from several rows together in one row (separated by comma)

I have a dataframe(based on a grouped object) like this:

  df:
         col2
   col1 
    a    ab
         cd
         ef
    b    kj
         jk
         l

What I want to get is this:

df:
   col1   col2
0   a      ab,cd,ef
1   b      kj,jk,l
2
.
.
.

So basically I want the strings from one 'group' as one 'string' column value. Does someone have an idea how to do this?

Upvotes: 1

Views: 84

Answers (1)

EdChum
EdChum

Reputation: 394159

IIUC then you groupby on level=0 of your index and apply a lambda to join the values:

In [175]:
df.groupby(level=0)['col2'].apply(lambda x: ','.join(x))

Out[175]:
col1
a    ab,cd,ef
b     kj,jk,l
Name: col2, dtype: object

Upvotes: 1

Related Questions