2014-05-08 47 views
0

逗號分隔字符串我有一個熊貓數據幀:轉換行到在大熊貓

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 

有誰知道如何做到這一點不留熊貓嗎?這似乎很簡單,但無法找到一種方法在熊貓內部做到這一點。

回答

6

從@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 
+1

我得到同樣的結果只用函數'拉姆達x: 「上」。加入(X)' – mtadd

+0

@mtadd yep..thanks – Jeff

+0

非常感謝傑夫和mtadd! – user690462