带分隔符的 Pandas groupby [英] Pandas groupby with delimiter join
本文介绍了带分隔符的 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=' ')
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
<小时>
更新:回答评论中的问题:
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
最后用于将索引或多索引转换为列:
Last for convert index or MultiIndex to columns:
df1 = df.groupby('col')['val'].agg('-'.join).reset_index(name='new')
这篇关于带分隔符的 Pandas groupby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文