电商 Python 访客Excel合并2

时间:2021-04-27 14:43:38   收藏:0   阅读:0
import pandas as pd
import os
import re

path = "./files/"
files = os.listdir(path)


# 用于存放Excel,里面的每个元素类型为:pandas.core.frame.DataFrame
list_excel = []

for filename in files:
    fullname = path + filename# excel的相对路径
    df = pd.read_excel(fullname)# 默认读取Excel的第一个表单
    
    col_name = df.columns.tolist()
    if ‘搜索关键字‘ not in col_name:
        # 插入列
        index = col_name.index(‘入店来源‘) + 1
        col_name.insert(index, ‘搜索关键字‘)
        df = df.reindex(columns = col_name)

        # 修改值
        df.loc[df[‘入店来源‘].str.find(‘手淘搜索‘) > -1 , ‘搜索关键字‘] = df[‘入店来源‘].str.replace(‘手淘搜索‘,‘‘)
        df.loc[df[‘入店来源‘].str.find(‘手淘搜索‘) > -1 , ‘入店来源‘] = ‘手淘搜索‘

    list_excel.append(df)# 把Excel追加到list中


writer = pd.ExcelWriter(‘test.xlsx‘)

# pd.concat:数据拼接
# to_excel:写入到Excel
pd.concat(list_excel).to_excel(writer,‘sheet1‘,index=False)

writer.save()

print(‘合并完成‘)

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!