在 pandas 中将行转换为逗号分隔的字符串 [英] Convert rows into comma separated string in pandas

查看:59
本文介绍了在 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' 列对其进行分组.

I need to group it using column 'a'.

df3 = df2.groupby(['a'])

接下来,我想将列 'b' 转换为逗号分隔的字符串,结果表应如下所示:

Next, I want to convert the column 'b' into comma-separated strings, the resulting table should look like this:

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.

推荐答案

edited from @DSM comment

edited from @DSM comment

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

这篇关于在 pandas 中将行转换为逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆