我有一个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']})
我需要使用列'a'
对其进行分组。
df3 = df2.groupby(['a'])
接下来,我想将列'b'
转换为逗号分隔的字符串,结果表应如下所示:
a b
---------------
one j, k, l
two m, n, o
three p, q
有没有人知道怎么做而不留下熊猫?看起来很简单,但找不到在熊猫里面做的方法。
答案 0 :(得分:7)
从@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