将行转换为逗号分隔字符串在pandas中
我有一个 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'])
接下来,我想把列 'b'
转换成用逗号分隔的字符串,最终的表格应该是这样的:
a b
---------------
one j, k, l
two m, n, o
three p, q
有没有人知道怎么在不离开 pandas 的情况下做到这一点?看起来很简单,但我找不到在 pandas 里面实现的方法。
1 个回答
12
根据@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