Pandas groupby与分隔符连接我尝试使用groupby对具有多个值的行进行分组。col valA CatA TigerB BallB Batimport pandas as pddf = pd.read_csv("Inputfile.txt", sep='\t')group = df.groupby(['col'])['val'].sum()我有A CatTigerB BallBat我想介绍一个分隔符,以便我的输出看起来像A Cat-TigerB Ball-Bat我试过了,group = df.groupby(['col'])['val'].sum().apply(lambda x: '-'.join(x))这产生了,A C-a-t-T-i-g-e-rB B-a-l-l-B-a-t这是什么问题?
2 回答
白衣非少年
TA贡献1155条经验 获得超0个赞
或者你也可以这样做:
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
添加回答
举报
0/150
提交
取消