【python 数据处理】分组求和、合并

来源:互联网 发布:mac查询端口使用情况 编辑:程序博客网 时间:2024/06/09 23:20
# encoding: utf-8import sysreload(sys)sys.setdefaultencoding('utf-8')import timeimport pandas as pdimport xlsxwritertime1 = time.time()import numpy as np#############读取数据##########################df=pd.read_excel('C:/pic/sample.xlsx')# 建立每个顾客的购买记录# print df##########################什么时候购买,买的产品单价###################################data1=pd.DataFrame({"Customer Account":df.iloc[:,4],"Date":df.iloc[:,0],"Product Name":df.iloc[:,3],"Qty":df.iloc[:,5],"Sale Price":df.iloc[:,7]})####################买了多少产品##################################df2 = data1.groupby(by=['Customer Account'])['Qty'].sum()data2=pd.DataFrame({"Customer Account":df2.index,"count":df2})###################合并data1和data2##############################data3=pd.merge(data1,data2,how='left',on='Customer Account')###########写出excel#################pd.DataFrame.to_excel(data3,'c:/result.xlsx',index=False)print u'数据处理完成'
原创粉丝点击