I imported a multi-sheet-excel file into Python.
code :
import_net_data = pd.read_excel(path_file, sheet_name=None)
sheets_name_tolerated = ['POSTE', 'DEPART 1', 'DEPART 2', 'DEPART 3', 'DEPART 4', 'DEPART 5', 'DEPART 6', 'DEPART 7', 'DEPART 8', 'DEPART 9', 'DEPART 10', 'DEPART 11', 'DEPART 12', 'DEPART 13', 'DEPART 14']
print(import_net_data.keys())
result:
dict_keys(['DEPART 1', 'DEPART 2', 'DEPART 3', 'DEPART 4', 'POSTE'])
I would like to check if the names of the excel sheet are matching the "sheets_name_tolerates" name. How can I proceed with the keys() that are given with pd.read_excel() function ?
I tried whithout any succes :
df.keys() in sheets_name_tolerated
Expected result :
True
Thanks in advance !
CodePudding user response:
The .keys() method on a dictionary is going to return a list
import_net_data = pd.read_excel(path_file, sheet_name=None)
sheets_name_tolerated = ['POSTE', 'DEPART 1', 'DEPART 2', 'DEPART 3', 'DEPART 4', 'DEPART 5', 'DEPART 6', 'DEPART 7', 'DEPART 8', 'DEPART 9', 'DEPART 10', 'DEPART 11', 'DEPART 12', 'DEPART 13', 'DEPART 14']
retrievedList=import_net_data.keys()
matches = [i for i in sheets_name_tolerated if i in retrievedList]
CodePudding user response:
Thanks BhavinT for the help !
Here is the final code that i will use :
import_net_data = pd.read_excel(path_file, sheet_name=None)
sheets_name_tolerated = ['POSTE', 'DEPART 1', 'DEPART 2', 'DEPART 3', 'DEPART 4', 'DEPART 5', 'DEPART 6', 'DEPART 7', 'DEPART 8', 'DEPART 9', 'DEPART 10', 'DEPART 11', 'DEPART 12', 'DEPART 13', 'DEPART 14']
matches = all([i in sheets_name_tolerated for i in import_net_data.keys()])
CodePudding user response:
.keys() doesn't return a list need to cast. Also, you can use in if list of lists. Not work for same size lists.
import_net_data = pd.read_excel(path_file, sheet_name=None)
sheets_name_tolerated = ['POSTE', 'DEPART 1', 'DEPART 2', 'DEPART 3', 'DEPART 4', 'DEPART 5', 'DEPART 6', 'DEPART 7', 'DEPART 8', 'DEPART 9', 'DEPART 10', 'DEPART 11', 'DEPART 12', 'DEPART 13', 'DEPART 14']
imported_sheet_names=import_net_data.keys()
# if you have or need exact match this should be work
print(list(import_net_data.keys()) == sheets_name_tolerated)
# if your number of list items and number of sheets are same but in different order
print(set(sheets_name_tolerated) == set(imported_sheet_names))
# if your excel file has only tolerated sheet names
print(all(map(sheets_name_tolerated.__contains__, imported_sheet_names)))

