![](/img/trans.png)
[英]How to merge .csv files into one .xls file in multiple sheets using Python?
[英]Appending all .xls files in a folder into one .csv file using Python
我有一个包含多个.xls文件的文件夹,我想将它们合并/附加到一个csv文件中。
我已经准备好脚本,但是我面临的问题是输出与输入的顺序不同,如果任何文件中的列名都不相同,则输出具有新列,例如:
Input1 Input2
col1 col2 col3 col1 col2 Col3
a1 a2 a3 b1 b2 b3
Output shown Output Expected
col1 col2 col3 Col3 col1 col2 col3
a1 a2 a3 NAN a1 a2 a3
b1 b2 NAN b3 b1 b2 b3
我当前的脚本:
#******************************************************************************************#
#* IMPORTING LIBRARIES *#
#******************************************************************************************#
import os as os
import pandas as pd
import time
start_time = time.time()
#******************************************************************************************#
# MERGING ALL THE FILES INTO ONE DATAFRAME *#
#******************************************************************************************#
input_path = os.getcwd()
files = os.listdir(input_path)
files
#******************************************************************************************#
# PICKING OUT ALL THE .XLS FILES *#
#******************************************************************************************#
files_xls = [f for f in files if f[-3:] in ('xls', '.xlsx', '.csv') ]
files_xls
#******************************************************************************************#
# APPENDING THE FILES INTO ONE DATAFRAME *#
#******************************************************************************************#
#Initializing one empty dataframe
master = pd.DataFrame()
for f in files_xls:
data = pd.read_excel(f)
master = master.append(data, ignore_index=True)
#******************************************************************************************#
# EXPORTING THE FILE INTO INTERIM LOCATION *#
#******************************************************************************************#
master.to_csv(input_path+'master.csv')
# Printing time taken in seconds
print("--- %s seconds ---" % (time.time() - start_time))
如果您需要输入,则可以在这里找到(下载任何文件):
https://www.rbi.org.in/Scripts/bs_viewcontent.aspx?Id=2009
尝试加载没有标题的文件并应用自定义文件,它看起来应该像这样:
for f in files_xls:
data = pd.read_excel(f,header=None,skiprows=0)
master = master.append(data, ignore_index=True)
master.columns = ['col1','col2',col3']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.