因为我经常要做数据拉取并合并存储在表格里,所以这里对我遇到的几种类型的表格合并进行讲解。
第一种就是columns是一样的,表格进行追加,如图
import glob,os
from numpy import *
#合并的表格放的路径
location='/Users/cuimengting/Desktop/wonderlab'
#获取全部是xlsx结尾的文件,如果是xls,csv 修改后缀即可
fileList=read_excel = glob.glob(os.path.join(location,'*.xlsx'))
df = None
#开始批量拿文件进行合并
for i,path in enumerate(fileList):
print(path)
month_ = pd.read_excel(path)
# 第一次df为空,需要赋值为DataFrame
if df is None:
df = month_
else:
#合并的方式,上下合并,可按需改成左右合并
df = pd.concat([df, month_], ignore_index=True)
#合并后的表格进行输出
df.to_excel('/Users/cuimengting/Desktop/wonderlab/频次.xlsx
第二种:不同表格进行合并,以所有表格的的index为基准 。
代码如下
import pandas as pd
import numpy as np
import glob,os
filearray=[]
filelocation=r"D:\code\cui\数据银行\自定义分析\自定义人群\data"
for filename in glob.glob(os.path.join(filelocation,"*xlsx")):
filearray.append(filename)
print(filearray)
filearray1=pd.read_excel(filearray[0])
filearray2=pd.read_excel(filearray[1])
datan=filearray1.merge(filearray2,on='标签',how='outer')
print(datan)
for data in filearray[2:len(filearray)+1]:
data=pd.read_excel(data)
#这里可以选择外链接:尽管有的表格没有这个标签,那么这个标签依然会被留下。
#内连接:inner,所有的表格都有这个标签,这个标签才会被留下。
datan=datan.merge(data,on='标签',how='outer')
downloadFile = datan
fileName = 'D:\code\cui\数据银行\自定义分析\自定义人群\data'+'.xlsx'
downloadFile.to_excel(fileName, encoding='utf8')