首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

python之表格数据批量合并

妈妈再也不用担心数据分析不会了,哪里不会点哪里 so easy!!!

还在为多个表格的合并焦头烂额吗?不管你的表格数据格式是.xls, .txt, 还是 .xlsx,一键分析就可以,下载python,一行代码,立马帮你全搞定。走过路过,不要错过,我都看了迫不及待,辣么给力,难道你还不转走吗?

# -*- coding: utf-8 -*-

import sys, os, argparse, os.path,re,math,time

import pandas as pd

import glob

#构建 参数

parser = argparse.ArgumentParser(description='This script is used to merge data for excel')

parser.add_argument('-t','--term',help='input merge term,required=True')

args = parser.parse_args()

#多个表格合并

current_path = os.chdir(sys.path[0])#sys.path[0] 获取python执行文件所在的绝对路径;并将其设定为工作路径

excel_files = os.listdir(current_path)#获取当前目录下的文件名

#批量转换当前路径下的表格格式

global separate_filepath

for excel_file in excel_files:

if separate_filepath[1] == ('.csv'):

excel_data = pd.read_csv(excel_file)

new_excel = excel_data.to_excel('%s.xlsx'%(separate_filepath[0]))

elif separate_filepath[1] == ('.xls'):

excel_data = pd.read_excel(excel_file)

new_excel = excel_data.to_excel('%s.xlsx'%(separate_filepath[0]))

elif separate_filepath[1] == ('.txt'):

excel_data = pd.read_table(excel_file)

new_excel = excel_data.to_excel('%s.xlsx'%(separate_filepath[0]))

excel_data = glob.glob('*.xlsx')#获取当前目录下‘.xlsx’的文件名

#2个表格合并

if len(excel_data) == 2:

a = pd.read_excel(excel_data[0])

b = pd.read_excel(excel_data[1])

data_merge = pd.merge(a,b,how = 'inner',on = '%s'%(args.term))

data_merge.to_excel('merge_result.xlsx')

#3个表格合并

if len(excel_data) == 3:

a = pd.read_excel(excel_data[0])

b = pd.read_excel(excel_data[1])

c = pd.read_excel(excel_data[2])

data_merge_1 = pd.merge(a,b,how = 'inner',on = '%s'%(args.term))

data_merge_2 = pd.merge(data_merge_1,c,how = 'inner',on = '%s'%(args.term))

data_merge_2.to_excel('merge_result.xlsx')

#4个表格合并

if len(excel_data) == 4:

a = pd.read_excel(excel_data[0])

b = pd.read_excel(excel_data[1])

c = pd.read_excel(excel_data[2])

d = pd.read_excel(excel_data[3])

data_merge_1 = pd.merge(a,b,how = 'inner',on = '%s'%(args.term))

data_merge_2 = pd.merge(data_merge_1,c,how = 'inner',on = '%s'%(args.term))

data_merge_3 = pd.merge(data_merge_2,d,how = 'inner',on = '%s'%(args.term))

data_merge_3.to_excel('merge_result.xlsx')

#删除运行过程中产生的文件‘.xlsx'

for i in range(0,len(excel_data)):

os.remove(excel_data[i])

使用方法:

(1)将上述代码保存成 test.py(或者其它文件的名字)

(2)将test.py和你的数据放在一个目录下

(3)运行cmd(dos界面)

(4)例如你要合并的列名是'GeneID' ,那么就是 python test.py -t GeneID

(5)新产生的文件名‘merge_result’就时运行的结果

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180428G1SECB00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券