码迷,mamicode.com
首页 > 其他好文 > 详细

20-pandas聚合

时间:2020-03-09 13:36:24      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:data   sum   numpy   group   聚合   merge   dex   pandas   avg   

import numpy as np
import pandas as pd
#1.聚合一次
df=pd.DataFrame({"age":[18,20,22,22,23,23],
                 "name":["A","B","C","D","E","F"],
                 "price1":[1000,900,800,700,600,600],
                 "price2":[10,9,8,7,6,6]})
print(df)
result1=df.groupby("age")["price1"]#按照age抓取price
print(result1.groups)
print(result1.sum())#总和
print(result1.mean())#平均
print(result1.max())
print(result1.min())

#2.聚合多次
d1={‘item‘:[‘萝卜‘,‘白菜‘,‘辣椒‘,‘冬瓜‘,‘萝卜‘,‘白菜‘,‘辣椒‘,‘冬瓜‘],
    ‘color‘:[‘white‘,‘white‘,‘red‘,‘green‘,‘white‘,‘white‘,‘red‘,‘green‘],
    ‘weight‘:[1,2,3,4,1,2,3,4],
    ‘price‘:[1,2,3,4,1,2,3,4]}
df=pd.DataFrame(d1)
result=df.groupby("color")["price"]
print(result.groups)
print(result.sum()["white"])
print(result.sum()["red"])
print(result.max()["white"])
print(result.mean()["white"])

result2=df.groupby("item")["price","weight"]
print(result2.groups)
print(result2.sum()["weight"]["萝卜"])
print(result2.sum()["weight"].萝卜)

sums=df.groupby("color").sum().add_prefix("avg__")
print(sums)
print(pd.merge(pd,sums,left_on="color",right_index=True))

  

20-pandas聚合

标签:data   sum   numpy   group   聚合   merge   dex   pandas   avg   

原文地址:https://www.cnblogs.com/wcyMiracle/p/12448064.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!