@@ -420,3 +420,139 @@ data = read_excel_sheets(file_path='Data_complete_Can_GPT_Replace_Human_Examiner
420420data.head(6 )
421421
422422```
423+
424+
425+ # ## save dictionary as json
426+ ```python
427+ def save_dict_as_json(d, filename):
428+ """
429+ Saves a dictionary as a JSON file, but only if the file does not already exist.
430+
431+ Parameters:
432+ d (dict): The dictionary to save.
433+ filename (str): The path and name of the file to save the dictionary to.
434+
435+ Raises:
436+ FileExistsError: If a file with the specified name alre exists.
437+ """
438+
439+ # Check if the file already exists
440+ if os.path.exists(filename):
441+ raise FileExistsError (f " File ' { filename} ' already exists. " )
442+
443+ # Create the directory if it does not exist
444+ os.makedirs(os.path.dirname(filename), exist_ok = True )
445+
446+ # Save the dictionary as a JSON file
447+ with open (filename, " w" ) as file :
448+ json.dump(d, file , indent = 4 )
449+
450+ # print_in_box(f"Result saved successfully at\n{filename}")
451+ ```
452+
453+
454+ # ## Read excel sheets
455+
456+ ```python
457+ def read_excel_sheets(file_path, sheets = None , return_type = " single" ):
458+ """
459+ Reads specified sheets from an Excel file using pandas.
460+
461+ :param file_path: str, path to the Excel file.
462+ :param sheets: str, int, or list, names or indices of the sheets to read.
463+ :param return_type: str, 'single' to return a single DataFrame (if one sheet is specified),
464+ 'dict' to return a dictionary of DataFrames (if multiple sheets are specified).
465+ :return: DataFrame or dict of DataFrames depending on return_type and sheets.
466+ """
467+ # Read the sheets based on the provided 'sheets' argument
468+ try :
469+ data = pd.read_excel(file_path, sheet_name = sheets)
470+ except Exception as e:
471+ print (f " Failed to read the file: { e} " )
472+ return None
473+
474+ # If multiple sheets are read into a dictionary
475+ if isinstance (data, dict ):
476+ if return_type == " single" :
477+ # If user wants a single DataFrame but multiple sheets were requested, raise an error
478+ raise ValueError (
479+ " Multiple sheets found but 'single' DataFrame requested. Specify correct 'return_type'."
480+ )
481+ return data
482+ else :
483+ if return_type == " dict" :
484+ # If user expects a dictionary but only one sheet was read, adjust the return structure
485+ return {sheets: data}
486+ return data
487+ ```
488+ # ## drop columns from padnas
489+
490+ ```python
491+ def drop_columns_from(df, start_column):
492+ """
493+ Drop all columns from the specified start_column to the end of the DataFrame (inclusive).
494+
495+ Parameters:
496+ df (pd.DataFrame): The DataFrame from which to drop columns.
497+ start_column (str): The column name from which to start dropping.
498+
499+ Returns:
500+ pd.DataFrame: A DataFrame with the specified columns removed.
501+ """
502+ # Get the index of the start column
503+ start_index = df.columns.get_loc(start_column)
504+
505+ # Get the column names to drop from start_index to the end
506+ columns_to_drop = df.columns[start_index:]
507+
508+ # Drop the columns
509+ df = df.drop(columns = columns_to_drop)
510+
511+ return df
512+ ```
513+
514+ # ## read csv with fallback
515+
516+ ```python
517+ def read_csv_with_fallback(primary_file, fallback_file):
518+ """
519+ Reads a CSV file into a DataFrame. If the primary file does not exist, it reads the fallback file.
520+
521+ Parameters:
522+ primary_file (str): The path to the primary CSV file.
523+ fallback_file (str): The path to the fallback CSV file.
524+
525+ Returns:
526+ pandas.DataFrame: DataFrame created from the read CSV file.
527+ """
528+ # Check if the primary file exists, if not, use the fallback file
529+ file_to_read = primary_file if os.path.exists(primary_file) else fallback_file
530+
531+ # Read the CSV file
532+ df = pd.read_csv(file_to_read)
533+
534+ return df
535+ ```
536+
537+ # ## Convert to three decimal place
538+
539+ ```python
540+ import ipywidgets as widgets
541+ from IPython.display import display
542+
543+ def round_to_three_decimals(number):
544+ rounded_number = round (number, 3 )
545+ return rounded_number
546+
547+ def on_click(btn):
548+ number = float (input_text.value)
549+ output_label.value = f " { round_to_three_decimals(number)} "
550+
551+ input_text = widgets.FloatText(description = " Number:" )
552+ submit_btn = widgets.Button(description = " Convert" )
553+ submit_btn.on_click(on_click)
554+ output_label = widgets.Label()
555+
556+ display(input_text, submit_btn, output_label)
557+ ** **
558+ ```
0 commit comments