Download parse_excel.py from DecodeMarketing/Correlation-network: direct link, hf CLI and curl.
- Browser
- Download file 8.51 kB
-
https://huggingface.co/spaces/DecodeMarketing/Correlation-network/resolve/main/parse_excel.py
- Command line
-
hf download hf://spaces/DecodeMarketing/Correlation-network/parse_excel.py
-
curl -L -o parse_excel.py https://huggingface.co/spaces/DecodeMarketing/Correlation-network/resolve/main/parse_excel.py
8.51 kB
| """Excel correlation file parsing and auto-detection.""" | |
| import pandas as pd | |
| # Fallback if detection fails (covers DE 6-territory and EN 10-territory models) | |
| _DEFAULT_REWARDS = [ | |
| 'Abenteuer', 'Autonomie', 'Disziplin', 'Sicherheit', 'Genuss', 'Erregung', | |
| 'Adventure', 'Autonomy', 'Discipline', 'Security', 'Enjoyment', 'Excitement', | |
| 'GreaterGood', 'Caring', 'Acceptance', 'Control', 'SelfPromotion', 'Achievement', 'Freedom', | |
| ] | |
| def detect_reward_territories(df): | |
| """Detect reward territory names from the Excel file. | |
| Row 4 (0-indexed row 3) contains section headers. The one with | |
| 'per reward field' marks the reward territory columns. Row 5 (0-indexed | |
| row 4) underneath lists the individual territory names. | |
| Returns: | |
| list of territory name strings, or _DEFAULT_REWARDS if detection fails. | |
| """ | |
| # Find the 'per reward field' header in row 4 (0-indexed row 3) | |
| reward_col_start = None | |
| for col_idx in range(df.shape[1]): | |
| val = df.iloc[3, col_idx] | |
| if pd.notna(val) and isinstance(val, str) and 'per reward field' in val.lower(): | |
| reward_col_start = col_idx | |
| break | |
| if reward_col_start is None: | |
| return list(_DEFAULT_REWARDS) | |
| # Read territory names from row 5 (0-indexed row 4) under that header | |
| territories = [] | |
| for col_idx in range(reward_col_start, df.shape[1]): | |
| val = df.iloc[4, col_idx] | |
| if pd.notna(val) and isinstance(val, str) and val.strip(): | |
| territories.append(val.strip()) | |
| else: | |
| break | |
| return territories if territories else list(_DEFAULT_REWARDS) | |
| def detect_data_start_row(df): | |
| """Find DATA_START_ROW by detecting the 2nd text block in column B. | |
| The Excel files have two data blocks: means (block 1) and deviations (block 2). | |
| We want block 2 (deviations) since those show what's distinctive. | |
| Returns: | |
| (row_number, blocks) where row_number is 1-based and blocks is a list | |
| of (start, end) tuples for each text block found. | |
| """ | |
| in_block = False | |
| block_start = None | |
| blocks = [] | |
| for row_idx in range(df.shape[0]): | |
| val = df.iloc[row_idx, 1] | |
| has_text = pd.notna(val) and isinstance(val, str) and len(str(val).strip()) > 0 | |
| if has_text and not in_block: | |
| in_block = True | |
| block_start = row_idx + 1 | |
| elif not has_text and in_block: | |
| in_block = False | |
| blocks.append((block_start, row_idx)) | |
| block_start = None | |
| if in_block: | |
| blocks.append((block_start, df.shape[0])) | |
| if len(blocks) >= 2: | |
| return blocks[1][0], blocks | |
| elif blocks: | |
| return blocks[0][0], blocks | |
| return None, [] | |
| def detect_cutoff_value(df): | |
| """Find CORR_THRESHOLD by searching for 'Cut-off used in columns' in column B. | |
| Note: This detection fails on all known real files — they don't contain this text. | |
| Falls back to the default (6.0) in the UI. | |
| """ | |
| for row_idx in range(df.shape[0]): | |
| val = df.iloc[row_idx, 1] | |
| if pd.notna(val) and isinstance(val, str) and 'cut-off used in columns' in val.lower(): | |
| for col_idx in range(df.shape[1]): | |
| cell_val = df.iloc[row_idx, col_idx] | |
| if pd.notna(cell_val) and isinstance(cell_val, (int, float)): | |
| return round(float(cell_val), 2) | |
| return None | |
| def detect_correlation_column_start(df): | |
| """Find CORR_COL_START by detecting first large column block (>50 cols) in row 5. | |
| Row 5 (0-indexed row 4) contains the column headers for the correlation matrix. | |
| The first block of >50 consecutive non-empty cells is the "mean across all brands" | |
| correlation matrix. | |
| """ | |
| in_block = False | |
| block_start = None | |
| col_blocks = [] | |
| for col_idx in range(df.shape[1]): | |
| val = df.iloc[4, col_idx] | |
| has_data = pd.notna(val) and str(val).strip() | |
| if has_data and not in_block: | |
| in_block = True | |
| block_start = col_idx | |
| elif not has_data and in_block: | |
| in_block = False | |
| col_blocks.append((block_start, col_idx - 1)) | |
| block_start = None | |
| if in_block: | |
| col_blocks.append((block_start, df.shape[1] - 1)) | |
| for start, end in col_blocks: | |
| if end - start + 1 > 50: | |
| return start | |
| return None | |
| def detect_nonrewards_patterns(df, data_start_idx, rewards_factors): | |
| """Count Rewards vs Nonrewards attributes starting from data_start_idx. | |
| Classification is based on whether the territory part of the variable code | |
| (3rd segment of PREFIX_PA_Territory_Attribute) appears in rewards_factors. | |
| """ | |
| rewards_count = 0 | |
| nonrewards_count = 0 | |
| rewards_set = set(rewards_factors) | |
| for row_idx in range(data_start_idx, min(data_start_idx + 200, df.shape[0])): | |
| code = df.iloc[row_idx, 1] | |
| if pd.notna(code) and isinstance(code, str): | |
| if '_PA_' in code: | |
| parts = code.split('_') | |
| if len(parts) >= 3: | |
| factor = parts[2] | |
| if factor in rewards_set: | |
| rewards_count += 1 | |
| else: | |
| nonrewards_count += 1 | |
| return {'Rewards': rewards_count, 'Nonrewards': nonrewards_count} | |
| def extract_network_data(df, data_start_row, corr_col_start, rewards_factors): | |
| """Extract attributes, codes, category indices, and correlation matrix from the Excel data. | |
| Args: | |
| df: Raw DataFrame (no header, 0-indexed) | |
| data_start_row: 1-based row number where deviation data starts | |
| corr_col_start: 0-based column index where correlation matrix starts | |
| rewards_factors: list of territory names classified as Rewards | |
| Returns: | |
| dict with keys: attribute_names, attribute_codes, category_indices, | |
| nonrewards_attrs, driver_names, corr_df | |
| """ | |
| data_start_idx = data_start_row - 1 | |
| rewards_set = set(rewards_factors) | |
| # Get driver codes from row 5 (0-indexed row 4) | |
| driver_codes = [] | |
| for col_idx in range(corr_col_start, df.shape[1]): | |
| driver_code = df.iloc[4, col_idx] | |
| if pd.notna(driver_code) and isinstance(driver_code, str) and driver_code.strip(): | |
| driver_codes.append(str(driver_code)) | |
| else: | |
| break | |
| # Get attributes from rows | |
| attribute_names = [] | |
| attribute_codes = [] | |
| category_indices = [] | |
| nonrewards_attrs = set() | |
| for row_idx in range(data_start_idx, df.shape[0]): | |
| attr_code = df.iloc[row_idx, 1] | |
| attr_name = df.iloc[row_idx, 2] | |
| cat_idx = df.iloc[row_idx, 3] | |
| if pd.notna(attr_name) and attr_name != '': | |
| code_str = str(attr_code) if pd.notna(attr_code) else '' | |
| attribute_codes.append(code_str) | |
| attribute_names.append(str(attr_name)) | |
| try: | |
| cat_val = float(cat_idx) if pd.notna(cat_idx) else 0 | |
| except (ValueError, TypeError): | |
| cat_val = 0 | |
| category_indices.append(cat_val) | |
| # Classify: if territory NOT in rewards → Nonreward | |
| if '_PA_' in code_str: | |
| parts = code_str.split('_') | |
| if len(parts) >= 3: | |
| factor = parts[2] | |
| if factor not in rewards_set: | |
| nonrewards_attrs.add(str(attr_name)) | |
| else: | |
| break | |
| # Map codes to display names | |
| code_to_name = dict(zip(attribute_codes, attribute_names)) | |
| driver_names = [code_to_name.get(code, code) for code in driver_codes] | |
| # Build correlation matrix | |
| corr_data = [] | |
| for row_idx in range(data_start_idx, data_start_idx + len(attribute_names)): | |
| row_data = [] | |
| for col_idx in range(corr_col_start, corr_col_start + len(driver_codes)): | |
| val = df.iloc[row_idx, col_idx] | |
| try: | |
| row_data.append(float(val) if pd.notna(val) else 0) | |
| except (ValueError, TypeError): | |
| row_data.append(0) | |
| corr_data.append(row_data) | |
| corr_df = pd.DataFrame(corr_data, index=attribute_names, columns=driver_names) | |
| return { | |
| 'attribute_names': attribute_names, | |
| 'attribute_codes': attribute_codes, | |
| 'category_indices': category_indices, | |
| 'nonrewards_attrs': nonrewards_attrs, | |
| 'driver_names': driver_names, | |
| 'corr_df': corr_df, | |
| 'attr_to_cat_idx': dict(zip(attribute_names, category_indices)), | |
| } | |