Здравствуйте, у меня есть данные в нескольких таблицах Excel, распределенных по разным подпапкам. До сих пор я смог написать код, который извлекает нужные столбцы и сохраняет их в словаре. Вот код:
import os
import pandas as pd
#Path to file using os
FOLDER_PATH = r'C:\Users\Sarah\Desktop\test'
def listDir(dir):
filenames = os.listdir(dir)
for filename in filenames:
print('File Name:'+ filename)
print('folder Path:'+ os.path.abspath(os.path.join(dir, filename)), sep='\n')
listDir(FOLDER_PATH)
#Display sheets names using pandas
pd.set_option('display.width',300)
mosul_file = (r'C:\Users\Sarah\Desktop\test\Months\March.xlsx')
mosul_file2 =(r'C:\Users\Sarah\Desktop\test\Months\April.xlsx')
mosul_file3 =(r'C:\Users\Sarah\Desktop\test\Months\May.xlsx')
mosul_file7 =(r'C:\Users\Sarah\Desktop\test\Months\July.xlsx')
xl = pd.ExcelFile(mosul_file)
xl2 = pd.ExcelFile(mosul_file2)
xl3 = pd.ExcelFile(mosul_file3)
xl7 = pd.ExcelFile(mosul_file7)
#Display headers index
mosul_df = xl.parse(0, header=[1], index_col=[0,1,2])
mosul_df2 = xl2.parse(0, header=[0], index_col=[0,1,2])
mosul_df3 = xl3.parse(0, header=[0], index_col=[0,1,2])
mosul_df7 = xl7.parse(1, header=[0], index_col=[0,1,2])
#Read Excel and Select columns
mosul_file = pd.read_excel(r'C:\Users\Sarah\Desktop\test\Months\March.xlsx', sheet_name = 0 ,
index_clo=None, na_values= ['NA'], usecols = "C , F ,G")
mosul_file2 = pd.read_excel(r'C:\Users\Sarah\Desktop\test\Months\April.xlsx', sheet_name = 0 ,
index_clo=None, na_values= ['NA'], usecols = "C , F , G")
mosul_file3 = pd.read_excel(r'C:\Users\Sarah\Desktop\test\Months\May.xlsx', sheet_name = 0 ,
index_clo=None, na_values= ['NA'], usecols = "C , F , G")
mosul_file7 = pd.read_excel(r'C:\Users\Sarah\Desktop\test\Months\July.xlsx', sheet_name = 0 ,
index_clo=None, na_values= ['NA'], usecols = "C, F, G")
#Remove NaN values
data_mosul_df = mosul_file.apply (pd.to_numeric, errors='coerce')
data_mosul_df = mosul_file.dropna()
data_mosul_df2 = mosul_file2.apply (pd.to_numeric, errors='coerce')
data_mosul_df2 = mosul_file2.dropna()
data_mosul_df3 = mosul_file3.apply (pd.to_numeric, errors='coerce')
data_mosul_df3 = mosul_file3.dropna()
data_mosul_df7 = mosul_file3.apply (pd.to_numeric, errors='coerce')
data_mosul_df7 = mosul_file7.dropna()
#Save to Dictionary
datamosul1 = data_mosul_df.to_dict()
datamosul2 = data_mosul_df2.to_dict()
datamosul3 = data_mosul_df3.to_dict()
datamosul7 = data_mosul_df7.to_dict()
Как сделать его автоматическим c, чтобы он просматривал все папки и подпапки? Спасибо