大 pandas :分割字符串,并计数值? [英] pandas: split string, and count values?

查看:57
本文介绍了大 pandas :分割字符串,并计数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据集,其中的列是逗号分隔的字符串,例如1,2,3,10:

I've got a pandas dataset with a column that's a comma-separated string, e.g. 1,2,3,10:

data = [
  { 'id': 1, 'score': 9, 'topics': '11,22,30' },
  { 'id': 2, 'score': 7, 'topics': '11,18,30' },
  { 'id': 3, 'score': 6, 'topics': '1,12,30' },
  { 'id': 4, 'score': 4, 'topics': '1,18,30' }
]
df = pd.DataFrame(data)

我想获得topics中每个值的计数和平均分数.所以:

I'd like to get a count and a mean score for each value in topics. So:

topic_id,count,mean
1,2,5
11,2,8
12,1,6

等.我该怎么办?

我已经了解到了

df['topic_ids'] = df.topics.str.split()

但是现在我想我要爆炸topic_ids了,所以整个值集中都有一个用于每个唯一值的列...?

But now I guess I want to explode topic_ids out, so there's a column for each unique value in the entire set of values...?

推荐答案

然后groupbyagg

df.topics=df.topics.str.split(',')
New_df=pd.DataFrame({'topics':np.concatenate(df.topics.values),'id':df.id.repeat(df.topics.apply(len)),'score':df.score.repeat(df.topics.apply(len))})

New_df.groupby('topics').score.agg(['count','mean'])

Out[1256]: 
        count  mean
topics             
1           2   5.0
11          2   8.0
12          1   6.0
18          2   5.5
22          1   9.0
30          4   6.5

这篇关于大 pandas :分割字符串,并计数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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