Как читать данные из файла Excel в python С ПУТЬМ ФАЙЛА КАК КОЛОННЫ в выводе - PullRequest
0 голосов
/ 17 апреля 2020
import pandas as pd
import numpy as np
import glob
import os

all_data = pd.DataFrame() 
rows = 0
for file in glob.glob("Ranking*.xlsx"):
    xls = pd.ExcelFile(file)
    sheets = xls.sheet_names

    for sheet_name in sheets:
        df = pd.read_excel(file, sheet_name='Output',header= 3)

    all_data = all_data.append(df, ignore_index = True)
    output_tab_data = all_data[['Supplier','Tariff','Region']]
    output_tab_data_no_NA = output_tab_data[output_tab_data.Supplier.notnull()]
    output_tab_data_no_NA ['file_source_name'] = os.path.abspath(file)

    print(output_tab_data_no_NA)    

Приведенный выше код создает эти столбцы на данный момент - «Поставщик», «Тариф», «Регион»

Но я хочу, чтобы это включало ДОПОЛНИТЕЛЬНУЮ КОЛОННУ с именем file_source_name - то есть Excel путь к имени файла из каждого загруженного файла Excel

1 Ответ

0 голосов
/ 18 апреля 2020
import pandas as pd
import numpy as np
import glob
import os

all_data = pd.DataFrame() #creating an empty data frame
rows = 0
for f in glob.glob("../<path where python is>/*.xlsx"): #import every file that ends in .xls
    xls = pd.ExcelFile(file)
    sheets = xls.sheet_names # To get names of all the sheets
    for sheet_name in sheets:
             df = pd.read_excel(file, sheet_name='Output',header= 3) #start copying data from line 4 in each file
             df['file_source_name'] = f  #append individual file name/file path
    all_data = all_data.append(df, ignore_index = True) #put all the copied data together
    output_tab_data = all_data[['Supplier','Tariff','Region','file_source_name']]
    output_tab_data_no_NA = output_tab_data[output_tab_data.Supplier.notnull()]
print(output_tab_data_no_NA)    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...