Python 带分隔符联接的Pandas groupby
我尝试使用groupby对具有多个值的行进行分组Python 带分隔符联接的Pandas groupby,python,python-3.x,pandas,pandas-groupby,Python,Python 3.x,Pandas,Pandas Groupby,我尝试使用groupby对具有多个值的行进行分组 col val A Cat A Tiger B Ball B Bat import pandas as pd df = pd.read_csv("Inputfile.txt", sep='\t') group = df.groupby(['col'])['val'].sum() 我得到 我想引入一个分隔符,这样我的输出看起来像 A Cat-Tiger B Ball-Bat 我试过了 group = df.groupby(['col'
col val
A Cat
A Tiger
B Ball
B Bat
import pandas as pd
df = pd.read_csv("Inputfile.txt", sep='\t')
group = df.groupby(['col'])['val'].sum()
我得到
我想引入一个分隔符,这样我的输出看起来像
A Cat-Tiger
B Ball-Bat
我试过了
group = df.groupby(['col'])['val'].sum().apply(lambda x: '-'.join(x))
这就产生了,
A C-a-t-T-i-g-e-r
B B-a-l-l-B-a-t
这里的问题是什么
谢谢
AP试试看
group = df.groupby(['col'])['val'].apply(lambda x: '-'.join(x))
或者,您可以这样做:
In [48]: df.groupby('col')['val'].agg('-'.join)
Out[48]:
col
A Cat-Tiger
B Ball-Bat
Name: val, dtype: object
更新:回答评论中的问题:
In [2]: df
Out[2]:
col val
0 A Cat
1 A Tiger
2 A Panda
3 B Ball
4 B Bat
5 B Mouse
6 B Egg
In [3]: df.groupby('col')['val'].agg('-'.join)
Out[3]:
col
A Cat-Tiger-Panda
B Ball-Bat-Mouse-Egg
Name: val, dtype: object
将索引或多索引转换为列的最后一步:
df1 = df.groupby('col')['val'].agg('-'.join).reset_index(name='new')
当一次将两行以上的行连接在一起时,这是否有效?我尝试使用新行字符连接行,结果是前两行用新行连接,其余行连接在一起,没有分隔符。添加了
reset\u index
,因为,可以自由修改答案。
df1 = df.groupby('col')['val'].agg('-'.join).reset_index(name='new')