带有分隔符的Pandas groupby加入
问题描述:
我尝试使用groupby对具有多个值的行进行分组.
I tried to use groupby to group rows with multiple values.
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 CatTiger
B BallBat
我想引入一个定界符,以便我的输出看起来像
I want to introduce a delimiter, so that my output looks like
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
答
或者您也可以这样:
In [48]: df.groupby('col')['val'].agg('-'.join)
Out[48]:
col
A Cat-Tiger
B Ball-Bat
Name: val, dtype: object
更新:从评论中回答问题:
UPDATE: answering question from the comment:
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
最后一次将索引或MultiIndex转换为列:
Last for convert index or MultiIndex to columns:
df1 = df.groupby('col')['val'].agg('-'.join).reset_index(name='new')