Reputation: 129
I have a pandas DataFrame:
from pandas import DataFrame
import pandas as pd
df2 = DataFrame({'a' : ['one', 'one', 'two','two', 'three', 'two', 'one', 'six'],
'b' : ['x', 'y', 'z', 'y', 'x', 'y', 'x', 'x']})
I need to group it using column 'a'
.
df3 = df2.groupby(['a'])
Next, I want to convert the column 'b'
into comma-separated strings, the resulting table should look like this:
a b
---------------
one j, k, l
two m, n, o
three p, q
Does anyone know how to do it without leaving pandas? It seems simple, but can't find a way to do it inside pandas.
Upvotes: 3
Views: 11784
Reputation: 129078
edited from @DSM comment
In [12]: df2.groupby('a')['b'].apply(','.join)
Out[12]:
a
one x,y,x
six x
three x
two z,y,y
Name: b, dtype: object
Upvotes: 13