文章转载自:微信公众号FunwithPython作者:一粒米比如在电商行业,有数以百万计的订单出货数据需要与仓库数据进行核对和计算,其中涉及数据计算。筛选、匹配等步骤,使用excel表超卡,经常卡。这时候,如果你懂Python,十几行代码就搞定了。这里需要两个Python库,一个是os库,一个是pandas库。os库os是Python中的内置库,不需要额外安装,只要用import导入就可以使用。os模块封装了常用的文件和目录操作,可以用来方便的对系统中的目录和文件进行各种操作,比如获取当前目录,列出当前文件夹下的所有文件和文件夹,判断文件是否存在等或者目录是否存在,删除文件等,具体见下图。pandas库pandas是一个第三方库,需要手动安装才能使用。Pandas是一个强大的专门用于数据分析的类库。它可以方便地从csv、Excel等文本文件和数据库中读取数据,然后对数据进行求和、计算平均值、计算方差、计算最大值和最小值。等数据分析,支持生成Excel等格式文件或可视化操作,功能如下:读取Excel需要依赖xlrd库,写入Excel需要依赖openpyxl,pandas、xlrd和openpyxl安装命令如下:$pipinstallxlrdopenpyxlpandas开始数据处理...这里假设数据是以日期命名的Excel文件,放在excel_data文件夹下。每个Excel文件包含用户ID、产品ID、产品属性列表、购买数量等信息。文件夹中的所有文件如下,在linux下用ls命令列举excel_data下所有文件:$lsexcel_data结果:20120702.xlsx20131018.xlsx20150203.xlsx20170416.xlsx20120703.xlsx20131019.xlsx20150204.xlsx20170417.xlsx20120704.xlsx20131020.xlsx20150205.xlsx20170418.xlsx20120705.xlsx20131021.xlsx20160101.xlsx20170419.xlsx...TheideaistousetheoslibrarytoobtainallExcelfiles,andthenusepandastoreadallthefilesinturnandmergethemtogetherfordata,Calculatethetotalamountofeachproductandthetoptenproductsinsales.1.ListallExcelfiles`importosfiles=os.listdir("excel_data")`2.Usepandastoreadallthedataandmergethemtogether`importpandasaspddf_list=[pd.read_excel(os.path.join("excel_data",f))forfinfiles]data=pd.concat(df_list)`3.Countthequantityofeachproduct`sum_of_product=data[["ProductID","PurchaseQuantity"]].groupby(["ProductID"]).sum()sum_of_product`结果购买数量商品ID166212018261720331967203320494203322332......12268002521122680026812269002316122692024481226960245获取销量前十的商品sum_of_product.sort_values('购买数量',ascending=False).head(10)结果:商品ID购买数量50018831566325000701682915001199363515001363663405000370063252111225823500105585248500160064948500066024692500025244123完整代码如下:`importosimportpandasaspd获取所有Excel文件并读取数据files=os.listdir("excel_data")df_list=[pd.read_excel(os.path.join("excel_data",f))forfinfiles]data=pd.concat(df_list)countsthequantityofeachproductandoutputsittoanExcelfilesum_of_product=data[["ProductID","PurchaseQuantity"]].groupby(["ProductID"]).sum()sum_of_product.to_excel("各商品数量统计.xlsx")统计销量前十的商品sum_of_product.sort_values('PurchaseQuantity',ascending=False).head(10)`结果:商品ID采购数量50018831566325000701682915001199363515001360113601130202632705823500105585248500160064948500066024692500025244123教程到此结束还有不足之处欢迎交流
