带有分隔符的Pandas groupby加入 [英] Pandas groupby with delimiter join

查看:103
本文介绍了带有分隔符的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')

这篇关于带有分隔符的Pandas groupby加入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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