居然快两年前写的还没发出来- 2019.3.16
先发了再说,发完我再慢慢改。
算成功了,但是不够完美,但是最终的源码好像不是这个,我要再找找,两年前的东西真的是历史悠久了。
问题概述
最近发现同事的工作中有一项是要每天制作商品销量透视表:从某个电商平台后台导出的订单明细,每天要手动勾选,生产透视表,还要把空值填充成0。而且从电商后台导出的csv中只有商品id,没有商品名称,需要手动试用VLOOKUP函数匹配。这种重复工作完全可以由python完成。
相关的文档、教程:
1、字典
python3-dictionary
这里将用到字典的get( )方法。
2、csv模块
3.6/library/csv.html
3、Pandas官方文档
pandas.pydata.org/pandas-docs/stable/
4、Openpyxl库官方文档
openpyxl.readthedocs.io/en/default/
步骤分解
1)读入csv数据,每天的记录数最多为几万条。
2) 在“商品id”列后插入一列“产品名称”,并用字典,将商品id对应的产品名称 写入到产品名称列。
*因为数据量不大,所以不考虑性能问题。如果量大,可能在生成透视表后再进行相关插入“产品名称”的操作更好。。
3)生成行字段: 商品id,列字段:仓库地点,求和项:销量的透视表,并将空值成0。
4)对数据透视表进行分割,使之符合相应的顺序要求。如“A仓库”列必须在“B仓库”列前,“A产品”行须在“B产品”行前。
源代码
字典替换好像失败了。
最后还是需要excel手动匹配一次商品id/商品名称,
但这样减少了很多手工劳动,多少都能快一点,还不会出错。
#职业道德原因,部分商业敏感内容已经替换,能理解到意思就行。
import csv
import pandas as pd
import numpy as np
from pandas import DataFrame,Series
import datetime
#with open("test.csv", "r", encoding= 'gbk') as datafile:
yesterday= datetime.datetime.today() - datetime.timedelta(1)
csvfilename = 'suppReport.csv'
df=pd.DataFrame(pd.read_csv(csvfilename,header = 0 ,encoding='gbk'))
#ss = df[['仓库编码']]
#ss.replace('xxxxx仓库','xx仓库')
#ss.replace('xxxxxx仓库','xx仓库')
# view first 3 records
print(df[:3])
'''
df2 = df.loc[:,['商品id','仓库编码','销量']]
sk = df2.unstack()
print(sk)
print('stacked')
'''
df_pivortable=pd.pivot_table(df,index=['商品id'],columns=['仓库编码'],
values=['销量'],aggfunc='sum',fill_value= 0,dropna=False)
#dataframed_pivortable = pd.crosstab(df, index=['商品id'],columns=['仓库编码'],
#values=['销量'],aggfunc='sum',fill_value= 0, dropna=False)
#dataframed_pivortable.fillna('0')
#dataframed_pivortable.drop([0])
dataframed_pivortable = pd.DataFrame(df_pivortable)
dataframed_pivortable.insert(0,'产品名称',0)
print(dataframed_pivortable)
print('executing...')
str_day_filename = ''XX店每日销量'+yesterday.strftime('%Y.%m.%d')+'.xlsx'
dataframed_pivortable.to_excel(str_day_filename, sheet_name='Sheet1')
# Manipulating in Excel
#Openpyxl is easier to manipulate than csv and pandas lib.
import openpyxl
stoday =yesterday.strftime('%m.%d')
str_day_filename = 'XX店每日销量'+yesterday.strftime('%Y.%m.%d')+'.xlsx'
wb = openpyxl.load_workbook(str_day_filename)
sheet = wb.get_sheet_by_name('Sheet1')
#the products and their updated price
#add the index of excel workbook,
# use list to control index
alphabet=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O',
'P','Q','R','S','T','U','V','W','X','Y','Z']
warelist_index=['C','D','E','F','G','H','I','J','K','L','M','N','O',
'P','Q','R','S','T','U','V','W','X','Y','Z',
'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ',
'AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ']
# warehouse dict
warehouse={'abdfsd仓':'ad仓','上海松江xx仓':'上海松江','合肥xx仓':'xx合肥',}
#官方仓库名称替换成常用简称
# product dict
proddict = {'123456':'可口可乐',
'123457':'百事可乐',
};
#举例
#todo:loop through the rows and update the prod name
print('matching from dict')
#change warehouse name to shorter form
for list_index in range(0,50):
list_element2 = warelist_index[list_index]+'2'
warehouse_key = sheet[list_element2].value
if warehouse_key in warehouse:
warehouse_key = str(warehouse_key)
sheet[list_element2]=warehouse.get(warehouse_key,'')
#match the id with product name
for i in range(4,100):
#skip the first row
k = sheet[('A'+str(i))].value
if k:
k = str(k)
cellb ='B'+str(i)
#print(cellb,k,type(k))
sheet[cellb] =proddict.get(k,'')
#print(sheet[cellb])
print('sucecced')
filename ='XX店销量-已匹配产品名'+stoday+'.xlsx'
wb.save(filename)
print('succeed!')
''' import csv
datalist=[]
csvfile=open('109.csv','r',encoding = 'gbk')
readcsv = csv.DictReader(csvfile)
row = ['id', 'storecode', 'sales']
save_ouoput = open("test.csv", "a", newline ='')
csv_writer = csv.writer(save_ouoput, dialect = "excel")
csv_writer.writerow(row) #wrirerow方法必须传入列表或元组才能整词写入,
#传入string则会出现i,l,k,e这种单字符写入方式
for column in readcsv:
d1=column['商品id']
d2=column['仓库编码']
d3=column['销量']
datalist=[d1,d2,d3]
#save_ouoput = open("test.csv", "a", newline ='')
csv_writer = csv.writer(save_ouoput, dialect='excel')
csv_writer.writerow(datalist)
print('done')
save_ouoput.close()
csvfile.close
# csvfile2=open('110.csv','r',encoding= 'gbk')
# check the output,to make sure if it's correct records
#print(column['商品id'],column['仓库编码'],column['销量'])
# csvsaver = csv.writer(csvfile,dialect = ('excel'))
'''
网友评论