Python 将行转换为以逗号分隔的字符串

Python 将行转换为以逗号分隔的字符串,python,pandas,Python,Pandas,我有一个数据框: 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']}) 我需要使用列'a'对其进行分组 df3 = df2.groupby(['a'])

我有一个数据框:

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']})
我需要使用列
'a'
对其进行分组

df3 = df2.groupby(['a'])
接下来,我想将列
'b'
转换为逗号分隔的字符串,结果表如下所示:

a       b
---------------

one     j, k, l

two     m, n, o

three   p, q

有人知道不离开熊猫怎么做吗?这看起来很简单,但在熊猫体内找不到一种方法

编辑自@DSM评论

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

我只使用函数
lambda x:“,”,就得到了相同的结果。加入(x)
非常感谢Jeff和mtadd!好的,如果我们真的想压缩,就没有必要使用
lambda
:我们可以直接
.apply(','.join)