Let us go through the Project requirement:-

1.Let us create One or Multiple dynamic lists of variables and save it in dictionary or Array or other datastructre for further repeating use in python. Variable names are in form of dynamic names for example Month_202401 to Month_202312 for 24 months( Take these 24 month backdated or as per current month’s Progression).

2.Later we will use this dictionary to create 24 csv files by filtering on year and month.

3.we will also use to create arrays based on this dynamic dictionary.

4.We will create custom excel files for 24 year months combination where column names are also in form of above 24 { year and months combination such as xyz_2404_04 to xyz_2404_12 , abc_xyz_2404_0405 to abc_xyz_2405_1201}.

Various Versions to Achieve it:-

import datetime
import pandas as pd
import os

# Step 1: Generate month names for the next 24 months
def generate_month_names():
    current_date = datetime.datetime.now()
    month_names = []

    for i in range(24):
        new_date = current_date + datetime.timedelta(days=30 * i)
        month_name = new_date.strftime("Month_%Y%m")
        month_names.append(month_name)
    
    return month_names

# Step 2: Create variables and store them in a dictionary
def create_variables(month_names):
    variables = {}
    for month in month_names:
        # Create some dummy data for demonstration
        data = pd.DataFrame({
            'Name': ['Alice', 'Bob', 'Charlie'],
            'Age': [25, 30, 35],
            'Month': [month] * 3
        })
        variables[month] = data
    
    return variables

# Step 3: Create CSV files from the dictionary
def create_csv_files(variables, output_directory):
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)

    for month, data in variables.items():
        file_name = f"{output_directory}/{month}.csv"
        data.to_csv(file_name, index=False)
        print(f"Saved {file_name}")

# Step 4: Create an Excel file with dynamic columns
def create_excel_file(variables, excel_file_name):
    with pd.ExcelWriter(excel_file_name) as writer:
        for month, data in variables.items():
            data.to_excel(writer, sheet_name=month, index=False)
        print(f"Saved {excel_file_name}")

# Main execution
if __name__ == "__main__":
    # Generate month names
    month_names = generate_month_names()
    
    # Create variables
    dynamic_vars = create_variables(month_names)
    
    # Directory to save CSV files
    output_directory = "output_csv_files"
    
    # Create CSV files
    create_csv_files(dynamic_vars, output_directory)
    
    # Excel file name
    excel_file_name = "dynamic_month_data.xlsx"
    
    # Create Excel file
    create_excel_file(dynamic_vars, excel_file_name)
import datetime
import pandas as pd
import os
from dateutil.relativedelta import relativedelta

# Step 1: Generate month names for the next 24 months
def generate_month_names():
    current_date = datetime.datetime.now()
    month_names = []

    for i in range(24):
        new_date = current_date + relativedelta(months=i)
        month_name = new_date.strftime("Month_%Y%m")
        month_names.append(month_name)
    
    return month_names

# Step 2: Create example data and store in a dictionary
def create_variables(month_names):
    variables = {}
    for month in month_names:
        # Create some example data for demonstration
        data = pd.DataFrame({
            'Name': ['Alice', 'Bob', 'Charlie'],
            'Age': [25, 30, 35],
            'Month': [month] * 3
        })
        variables[month] = data
    
    return variables

# Step 3: Create CSV files from the dictionary
def create_csv_files(variables, output_directory):
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)

    for month, data in variables.items():
        file_name = f"{output_directory}/{month}.csv"
        data.to_csv(file_name, index=False)
        print(f"Saved {file_name}")

# Step 4: Create arrays based on the data stored in the dictionary
def create_arrays(variables):
    arrays = {}
    for month, data in variables.items():
        arrays[month] = data.values
    return arrays

# Step 5: Create custom Excel files for 24-month combinations
def create_custom_excel_files(variables, excel_file_name):
    with pd.ExcelWriter(excel_file_name) as writer:
        for i, (month, data) in enumerate(variables.items()):
            # Generate custom column names
            custom_columns = [f"xyz_{month}_{j+1:02d}" for j in range(len(data.columns))]
            custom_data = data.copy()
            custom_data.columns = custom_columns
            custom_data.to_excel(writer, sheet_name=month, index=False)
        
        # Example of creating more complex column names and data combination
        for i in range(1, 25):
            month_name = f"abc_xyz_{variables[list(variables.keys())[i-1]].iloc[0]['Month']}_{variables[list(variables.keys())[i%24]].iloc[0]['Month']}"
            complex_data = pd.concat([variables[list(variables.keys())[i-1]], variables[list(variables.keys())[i%24]]], axis=1)
            complex_data.columns = [f"{month_name}_{col}" for col in complex_data.columns]
            complex_data.to_excel(writer, sheet_name=month_name, index=False)
        
        print(f"Saved {excel_file_name}")

# Main execution
if __name__ == "__main__":
    # Generate month names
    month_names = generate_month_names()
    
    # Create example data and store in a dictionary
    dynamic_vars = create_variables(month_names)
    
    # Directory to save CSV files
    output_directory = "output_csv_files"
    
    # Create CSV files
    create_csv_files(dynamic_vars, output_directory)
    
    # Create arrays based on the data stored in the dictionary
    arrays = create_arrays(dynamic_vars)
    print("Created arrays based on the dictionary.")
    
    # Excel file name
    excel_file_name = "dynamic_month_data.xlsx"
    
    # Create custom Excel files
    create_custom_excel_files(dynamic_vars, excel_file_name)
from datetime import date, timedelta

def generate_month_names(months):
  """
  Generates a list of dynamic variable names representing month names
  based on the provided number of months in the past.

  Args:
      months (int): The number of months to consider (including the current month).

  Returns:
      list: A list of strings representing dynamic month variable names.
  """
  current_date = date.today()
  month_names = []
  for i in range(months):
    month = current_date - timedelta(days=i * 31)  # Adjust for approximate month length
    month_name = f"Month_{month.year}{month.month:02d}"
    month_names.append(month_name)
  return month_names

def create_data_structure(month_names):
  """
  Creates a dictionary where keys are dynamic month names and values are
  empty lists (to be populated with data later).

  Args:
      month_names (list): A list of dynamic month variable names.

  Returns:
      dict: A dictionary with dynamic month names as keys and empty lists as values.
  """
  data_structure = {}
  for month_name in month_names:
    data_structure[month_name] = []
  return data_structure

def create_csv_files(data_structure):
  """
  Creates CSV files for each month in the data structure with appropriate column names.

  Args:
      data_structure (dict): A dictionary with dynamic month names as keys and lists as values.
  """
  for month_name, data in data_structure.items():
    year, month = month_name.split("_")[1:]
    # Sample data for illustration. Replace with your actual data
    data.append(["col1", "col2", "col3"])
    filename = f"{month_name}.csv"
    with open(filename, "w", newline="") as csvfile:
      writer = csv.writer(csvfile)
      writer.writerow([f"xyz_{year}{month:02d}_{d:02d}" for d in range(4, 13)])  # Sample column names
      writer.writerows(data)

def create_excel_files(data_structure):
  """
  Creates custom Excel files (using a library like openpyxl) for each month,
  with dynamic column names based on year and month combinations.

  **Note:** This requires an external library like openpyxl for Excel manipulation.

  Args:
      data_structure (dict): A dictionary with dynamic month names as keys and lists as values.
  """
  # Replace this with your Excel file creation logic using a library like openpyxl
  pass

# Example Usage
months = 24
month_names = generate_month_names(months)
data_structure = create_data_structure(month_names)

# Populate data_structure with your actual data for each month

create_csv_files(data_structure)
create_excel_files(data_structure)  # Requires an external library

print("Data structures and files created successfully!")

Discover more from AI HintsToday

Subscribe to get the latest posts sent to your email.

Discover more from AI HintsToday

Subscribe now to keep reading and get access to the full archive.

Continue reading