前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Pandas GroupBy 使用教程

Pandas GroupBy 使用教程

作者头像
致Great
发布2019-01-28 15:45:56
2K0
发布2019-01-28 15:45:56
举报
文章被收录于专栏:程序生活程序生活

实例 1 将分组后的字符拼接

import pandas as pd
df=pd.DataFrame({
    'user_id':[1,2,1,3,3],
    'content_id':[1,1,2,2,2],
    'tag':['cool','nice','clever','clever','not-bad']
})
df

将df按content_id分组,然后将每组的tag用逗号拼接

df.groupby('content_id')['tag'].apply(lambda x:','.join(x)).to_frame()

实例2 统计每个content_id有多少个不同的用户

import pandas as pd

df = pd.DataFrame({
    'user_id':[1,2,1,3,3,],
    'content_id':[1,1,2,2,2],
    'tag':['cool','nice','clever','clever','not-bad']
})

df.groupby("content_id")["user_id"].nunique().to_frame()

实例3 分组结果排序

import pandas as pd

df = pd.DataFrame({
    'value':[20.45,22.89,32.12,111.22,33.22,100.00,99.99],
    'product':['table','chair','chair','mobile phone','table','mobile phone','table']
})
df
df1 = df.groupby('product')['value'].sum().to_frame().reset_index()
df1

按产品product分组后,然后value求和:

df2 = df.groupby('product')['value'].sum().to_frame().reset_index().sort_values(by='value')
df2

实例4 分组大小绘图

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({
    'value':[20.45,22.89,32.12,111.22,33.22,100.00,99.99],
    'product':['table','chair','chair','mobile phone','table','mobile phone','table']
})
df
plt.clf()
df.groupby('product').size().plot(kind='bar')
plt.show()

实例5 分组求和绘图

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({
    'value':[20.45,22.89,32.12,111.22,33.22,100.00,99.99],
    'product':['table','chair','chair','mobile phone','table','mobile phone','table']
})
df
plt.clf()
df.groupby('product').sum().plot(kind='bar')
plt.show()

实例 6 使用agg函数

import pandas as pd

df = pd.DataFrame({
    'value':[20.45,22.89,32.12,111.22,33.22,100.00,99.99],
    'product':['table','chair','chair','mobile phone','table','mobile phone','table']
})

grouped_df = df.groupby('product').agg({'value':['min','max','mean']})
grouped_df
grouped_df.columns = ['_'.join(col).strip() for col in grouped_df.columns.values]
grouped_df = grouped_df.reset_index()
grouped_df

实例7 遍历分组

for key,group_df in df.groupby('product'):
    print("the group for product '{}' has {} rows".format(key,len(group_df)))  
the group for product 'chair' has 2 rows
the group for product 'mobile phone' has 2 rows
the group for product 'table' has 3 rows
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.01.20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 实例 1 将分组后的字符拼接
  • 实例2 统计每个content_id有多少个不同的用户
  • 实例3 分组结果排序
  • 实例4 分组大小绘图
  • 实例5 分组求和绘图
  • 实例 6 使用agg函数
  • 实例7 遍历分组
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档