pandas 在熊猫中将行转换为逗号分隔的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23544879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert rows into comma separated string in pandas
提问by user690462
I have a pandas DataFrame:
我有一个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']})
I need to group it using column 'a'.
我需要使用 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:
接下来,我想将该列'b'转换为逗号分隔的字符串,结果表应如下所示:
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.
有谁知道如何在不离开Pandas的情况下做到这一点?看起来很简单,但是在pandas里面找不到办法。
回答by Jeff
edited from @DSM comment
从@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

