Spaces:
Sleeping
Sleeping
Upload Data_Import.py
Browse files- Data_Import.py +172 -212
Data_Import.py
CHANGED
|
@@ -8,11 +8,10 @@ st.set_page_config(
|
|
| 8 |
initial_sidebar_state="collapsed",
|
| 9 |
)
|
| 10 |
|
|
|
|
| 11 |
import numpy as np
|
| 12 |
import pandas as pd
|
| 13 |
from utilities import set_header, load_local_css, load_authenticator
|
| 14 |
-
import pickle
|
| 15 |
-
|
| 16 |
|
| 17 |
load_local_css("styles.css")
|
| 18 |
set_header()
|
|
@@ -116,60 +115,6 @@ def files_to_dataframes(uploaded_files):
|
|
| 116 |
|
| 117 |
|
| 118 |
# Function to adjust dataframe granularity
|
| 119 |
-
# def adjust_dataframe_granularity(df, current_granularity, target_granularity):
|
| 120 |
-
# # Set index
|
| 121 |
-
# df.set_index("date", inplace=True)
|
| 122 |
-
|
| 123 |
-
# # Define aggregation rules for resampling
|
| 124 |
-
# aggregation_rules = {
|
| 125 |
-
# col: "sum" if pd.api.types.is_numeric_dtype(df[col]) else "first"
|
| 126 |
-
# for col in df.columns
|
| 127 |
-
# }
|
| 128 |
-
|
| 129 |
-
# resampled_df = df
|
| 130 |
-
# if current_granularity == "daily" and target_granularity == "weekly":
|
| 131 |
-
# resampled_df = df.resample("W-MON").agg(aggregation_rules)
|
| 132 |
-
|
| 133 |
-
# elif current_granularity == "daily" and target_granularity == "monthly":
|
| 134 |
-
# resampled_df = df.resample("MS").agg(aggregation_rules)
|
| 135 |
-
|
| 136 |
-
# elif current_granularity == "daily" and target_granularity == "daily":
|
| 137 |
-
# resampled_df = df.resample("D").agg(aggregation_rules)
|
| 138 |
-
|
| 139 |
-
# elif current_granularity in ["weekly", "monthly"] and target_granularity == "daily":
|
| 140 |
-
# # For higher to lower granularity, distribute numeric and replicate non-numeric values equally across the new period
|
| 141 |
-
# expanded_data = []
|
| 142 |
-
# for _, row in df.iterrows():
|
| 143 |
-
# if current_granularity == "weekly":
|
| 144 |
-
# period_range = pd.date_range(start=row.name, periods=7)
|
| 145 |
-
# elif current_granularity == "monthly":
|
| 146 |
-
# period_range = pd.date_range(
|
| 147 |
-
# start=row.name, periods=row.name.days_in_month
|
| 148 |
-
# )
|
| 149 |
-
|
| 150 |
-
# for date in period_range:
|
| 151 |
-
# new_row = {}
|
| 152 |
-
# for col in df.columns:
|
| 153 |
-
# if pd.api.types.is_numeric_dtype(df[col]):
|
| 154 |
-
# if current_granularity == "weekly":
|
| 155 |
-
# new_row[col] = row[col] / 7
|
| 156 |
-
# elif current_granularity == "monthly":
|
| 157 |
-
# new_row[col] = row[col] / row.name.days_in_month
|
| 158 |
-
# else:
|
| 159 |
-
# new_row[col] = row[col]
|
| 160 |
-
# expanded_data.append((date, new_row))
|
| 161 |
-
|
| 162 |
-
# resampled_df = pd.DataFrame(
|
| 163 |
-
# [data for _, data in expanded_data],
|
| 164 |
-
# index=[date for date, _ in expanded_data],
|
| 165 |
-
# )
|
| 166 |
-
|
| 167 |
-
# # Reset index
|
| 168 |
-
# resampled_df = resampled_df.reset_index().rename(columns={"index": "date"})
|
| 169 |
-
|
| 170 |
-
# return resampled_df
|
| 171 |
-
|
| 172 |
-
|
| 173 |
def adjust_dataframe_granularity(df, current_granularity, target_granularity):
|
| 174 |
# Set index
|
| 175 |
df.set_index("date", inplace=True)
|
|
@@ -229,39 +174,47 @@ def adjust_dataframe_granularity(df, current_granularity, target_granularity):
|
|
| 229 |
return resampled_df
|
| 230 |
|
| 231 |
|
| 232 |
-
# Function to clean and extract unique values of
|
| 233 |
st.cache_resource(show_spinner=False)
|
| 234 |
|
| 235 |
|
| 236 |
def clean_and_extract_unique_values(files_dict, selections):
|
| 237 |
-
|
| 238 |
-
|
| 239 |
|
| 240 |
for file_name, file_data in files_dict.items():
|
| 241 |
df = file_data["df"]
|
| 242 |
|
| 243 |
-
# '
|
| 244 |
-
|
| 245 |
-
|
| 246 |
|
| 247 |
-
# Clean and standardize
|
| 248 |
-
if
|
| 249 |
-
|
| 250 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
)
|
| 252 |
-
|
| 253 |
|
| 254 |
-
# Clean and standardize
|
| 255 |
-
if
|
| 256 |
-
|
| 257 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
)
|
| 259 |
-
|
| 260 |
|
| 261 |
# Update the processed DataFrame back in the dictionary
|
| 262 |
files_dict[file_name]["df"] = df
|
| 263 |
|
| 264 |
-
return
|
| 265 |
|
| 266 |
|
| 267 |
# Function to format values for display
|
|
@@ -302,19 +255,21 @@ def apply_granularity_to_all(files_dict, granularity_selection, selections):
|
|
| 302 |
for file_name, file_data in files_dict.items():
|
| 303 |
df = file_data["df"].copy()
|
| 304 |
|
| 305 |
-
# Handling when
|
| 306 |
-
|
| 307 |
-
|
| 308 |
|
| 309 |
# Correcting the segment selection logic & handling 'N/A'
|
| 310 |
-
if
|
| 311 |
-
unique_combinations = df[
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
|
|
|
|
|
|
| 318 |
else:
|
| 319 |
# If both are 'N/A', process the entire dataframe as is
|
| 320 |
df = adjust_dataframe_granularity(
|
|
@@ -325,15 +280,15 @@ def apply_granularity_to_all(files_dict, granularity_selection, selections):
|
|
| 325 |
|
| 326 |
transformed_segments = []
|
| 327 |
for _, combo in unique_combinations.iterrows():
|
| 328 |
-
if
|
| 329 |
segment = df[
|
| 330 |
-
(df[
|
| 331 |
-
& (df[
|
| 332 |
]
|
| 333 |
-
elif
|
| 334 |
-
segment = df[df[
|
| 335 |
-
elif
|
| 336 |
-
segment = df[df[
|
| 337 |
|
| 338 |
# Adjust granularity of the segment
|
| 339 |
transformed_segment = adjust_dataframe_granularity(
|
|
@@ -353,7 +308,7 @@ st.cache_resource(show_spinner=False)
|
|
| 353 |
|
| 354 |
|
| 355 |
def create_main_dataframe(
|
| 356 |
-
files_dict,
|
| 357 |
):
|
| 358 |
# Determine the global start and end dates across all DataFrames
|
| 359 |
global_start = min(df["df"]["date"].min() for df in files_dict.values())
|
|
@@ -369,18 +324,18 @@ def create_main_dataframe(
|
|
| 369 |
else: # Default to daily if not weekly or monthly
|
| 370 |
date_range = pd.date_range(start=global_start, end=global_end, freq="D")
|
| 371 |
|
| 372 |
-
# Collect all unique
|
| 373 |
-
|
| 374 |
-
|
| 375 |
|
| 376 |
-
# Dynamically build the list of dimensions (
|
| 377 |
dimensions, merge_keys = [], []
|
| 378 |
-
if
|
| 379 |
-
dimensions.append(
|
| 380 |
-
merge_keys.append("
|
| 381 |
-
if
|
| 382 |
-
dimensions.append(
|
| 383 |
-
merge_keys.append("
|
| 384 |
|
| 385 |
dimensions.append(date_range) # Date range is always included
|
| 386 |
merge_keys.append("date") # Date range is always included
|
|
@@ -402,28 +357,28 @@ def merge_into_main_df(main_df, files_dict, selections):
|
|
| 402 |
for file_name, file_data in files_dict.items():
|
| 403 |
df = file_data["df"].copy()
|
| 404 |
|
| 405 |
-
# Rename selected
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
if
|
| 409 |
-
df.rename(columns={
|
| 410 |
-
if
|
| 411 |
-
df.rename(columns={
|
| 412 |
|
| 413 |
-
# Merge current DataFrame into main_df based on 'date', and where applicable, '
|
| 414 |
merge_keys = ["date"]
|
| 415 |
-
if "
|
| 416 |
-
merge_keys.append("
|
| 417 |
-
if "
|
| 418 |
-
merge_keys.append("
|
| 419 |
main_df = pd.merge(main_df, df, on=merge_keys, how="left")
|
| 420 |
|
| 421 |
# After all merges, sort by 'date' and reset index for cleanliness
|
| 422 |
sort_by = ["date"]
|
| 423 |
-
if "
|
| 424 |
-
sort_by.append("
|
| 425 |
-
if "
|
| 426 |
-
sort_by.append("
|
| 427 |
main_df.sort_values(by=sort_by, inplace=True)
|
| 428 |
main_df.reset_index(drop=True, inplace=True)
|
| 429 |
|
|
@@ -478,16 +433,16 @@ def prepare_missing_stats_df(df):
|
|
| 478 |
missing_stats = []
|
| 479 |
for column in df.columns:
|
| 480 |
if (
|
| 481 |
-
column == "date" or column == "
|
| 482 |
-
): # Skip Date,
|
| 483 |
continue
|
| 484 |
|
| 485 |
missing = df[column].isnull().sum()
|
| 486 |
pct_missing = round((missing / len(df)) * 100, 2)
|
| 487 |
|
| 488 |
# Dynamically assign category based on column name
|
| 489 |
-
|
| 490 |
-
category = "Media"
|
| 491 |
|
| 492 |
missing_stats.append(
|
| 493 |
{
|
|
@@ -527,12 +482,21 @@ def add_api_dataframe_to_dict(main_df, files_dict):
|
|
| 527 |
# Function to reads an API into a DataFrame, parsing specified columns as datetime
|
| 528 |
@st.cache_resource(show_spinner=False)
|
| 529 |
def read_API_data():
|
| 530 |
-
return pd.read_excel(
|
| 531 |
|
| 532 |
|
| 533 |
-
# Function to set the '
|
| 534 |
-
def
|
| 535 |
-
st.session_state["
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 536 |
|
| 537 |
|
| 538 |
# Initialize 'final_df' in session state
|
|
@@ -543,9 +507,9 @@ if "final_df" not in st.session_state:
|
|
| 543 |
if "bin_dict" not in st.session_state:
|
| 544 |
st.session_state["bin_dict"] = {}
|
| 545 |
|
| 546 |
-
# Initialize '
|
| 547 |
-
if "
|
| 548 |
-
st.session_state["
|
| 549 |
|
| 550 |
# Page Title
|
| 551 |
st.write("") # Top padding
|
|
@@ -553,7 +517,7 @@ st.title("Data Import")
|
|
| 553 |
|
| 554 |
|
| 555 |
#########################################################################################################################################################
|
| 556 |
-
# Create a dictionary to hold all DataFrames and collect user input to specify "
|
| 557 |
#########################################################################################################################################################
|
| 558 |
|
| 559 |
|
|
@@ -568,25 +532,25 @@ uploaded_files = st.file_uploader(
|
|
| 568 |
"Upload additional data",
|
| 569 |
type=["xlsx"],
|
| 570 |
accept_multiple_files=True,
|
| 571 |
-
on_change=
|
| 572 |
)
|
| 573 |
|
| 574 |
# Custom HTML for upload instructions
|
| 575 |
recommendation_html = f"""
|
| 576 |
<div style="text-align: justify;">
|
| 577 |
-
<strong>Recommendation:</strong> For optimal processing, please ensure that all uploaded datasets including
|
| 578 |
</div>
|
| 579 |
"""
|
| 580 |
st.markdown(recommendation_html, unsafe_allow_html=True)
|
| 581 |
|
| 582 |
-
# Choose
|
| 583 |
-
st.markdown("#### Choose
|
| 584 |
# Granularity Selection
|
| 585 |
granularity_selection = st.selectbox(
|
| 586 |
"Choose Date Granularity",
|
| 587 |
["Daily", "Weekly", "Monthly"],
|
| 588 |
label_visibility="collapsed",
|
| 589 |
-
on_change=
|
| 590 |
)
|
| 591 |
granularity_selection = str(granularity_selection).lower()
|
| 592 |
|
|
@@ -606,10 +570,10 @@ if not files_dict:
|
|
| 606 |
st.stop() # Halts further execution until file is uploaded
|
| 607 |
|
| 608 |
|
| 609 |
-
# Select
|
| 610 |
-
st.markdown("#### Select
|
| 611 |
selections = {}
|
| 612 |
-
with st.expander("Select
|
| 613 |
count = 0 # Initialize counter to manage the visibility of labels and keys
|
| 614 |
for file_name, file_data in files_dict.items():
|
| 615 |
# Determine visibility of the label based on the count
|
|
@@ -621,22 +585,22 @@ with st.expander("Select DMA and Panel columns", expanded=False):
|
|
| 621 |
# Extract non-numeric columns
|
| 622 |
non_numeric_cols = file_data["non_numeric"]
|
| 623 |
|
| 624 |
-
# Prepare
|
| 625 |
-
|
| 626 |
-
|
| 627 |
|
| 628 |
# Skip if only one option is available
|
| 629 |
-
if len(
|
| 630 |
-
|
| 631 |
-
# Update the selections for
|
| 632 |
selections[file_name] = {
|
| 633 |
-
"
|
| 634 |
-
"
|
| 635 |
}
|
| 636 |
continue
|
| 637 |
|
| 638 |
-
# Create layout columns for File Name,
|
| 639 |
-
file_name_col,
|
| 640 |
|
| 641 |
with file_name_col:
|
| 642 |
# Display "File Name" label only for the first file
|
|
@@ -646,45 +610,45 @@ with st.expander("Select DMA and Panel columns", expanded=False):
|
|
| 646 |
st.write("")
|
| 647 |
st.write(file_name) # Display the file name
|
| 648 |
|
| 649 |
-
with
|
| 650 |
-
# Display a selectbox for
|
| 651 |
-
|
| 652 |
-
"Select
|
| 653 |
-
|
| 654 |
-
on_change=
|
| 655 |
label_visibility=label_visibility, # Control visibility of the label
|
| 656 |
-
key=f"
|
| 657 |
)
|
| 658 |
|
| 659 |
-
with
|
| 660 |
-
# Display a selectbox for
|
| 661 |
-
|
| 662 |
-
"Select Panel",
|
| 663 |
-
|
| 664 |
-
on_change=
|
| 665 |
label_visibility=label_visibility, # Control visibility of the label
|
| 666 |
-
key=f"
|
| 667 |
)
|
| 668 |
|
| 669 |
-
# Skip processing if the same column is selected for both
|
| 670 |
-
if
|
| 671 |
-
|
| 672 |
):
|
| 673 |
st.warning(
|
| 674 |
-
f"File: {file_name} → The same column cannot serve as both
|
| 675 |
)
|
| 676 |
-
|
| 677 |
st.stop()
|
| 678 |
|
| 679 |
-
# Update the selections for
|
| 680 |
selections[file_name] = {
|
| 681 |
-
"
|
| 682 |
-
"
|
| 683 |
}
|
| 684 |
|
| 685 |
count += 1 # Increment the counter after processing each file
|
| 686 |
|
| 687 |
-
# Accept
|
| 688 |
if st.button("Accept and Process", use_container_width=True):
|
| 689 |
|
| 690 |
# Normalize all data to a daily granularity. This initial standardization simplifies subsequent conversions to other levels of granularity
|
|
@@ -697,38 +661,38 @@ with st.expander("Select DMA and Panel columns", expanded=False):
|
|
| 697 |
)
|
| 698 |
|
| 699 |
st.session_state["files_dict"] = files_dict
|
| 700 |
-
st.session_state["
|
| 701 |
|
| 702 |
|
| 703 |
#########################################################################################################################################################
|
| 704 |
-
# Display unique
|
| 705 |
#########################################################################################################################################################
|
| 706 |
|
| 707 |
|
| 708 |
-
# Halts further execution until
|
| 709 |
-
if "files_dict" in st.session_state and st.session_state["
|
| 710 |
files_dict = st.session_state["files_dict"]
|
| 711 |
else:
|
| 712 |
st.stop()
|
| 713 |
|
| 714 |
-
# Set to store unique values of
|
| 715 |
-
with st.spinner("Fetching
|
| 716 |
-
|
| 717 |
files_dict, selections
|
| 718 |
)
|
| 719 |
|
| 720 |
-
# List of
|
| 721 |
-
|
| 722 |
-
|
| 723 |
|
| 724 |
-
# Format
|
| 725 |
-
|
| 726 |
-
|
| 727 |
|
| 728 |
-
# Unique
|
| 729 |
-
st.markdown("#### Unique
|
| 730 |
-
# Display
|
| 731 |
-
with st.expander("Unique
|
| 732 |
st.write("")
|
| 733 |
st.markdown(
|
| 734 |
f"""
|
|
@@ -738,20 +702,20 @@ with st.expander("Unique DMA and Panel values"):
|
|
| 738 |
}}
|
| 739 |
</style>
|
| 740 |
<div class="justify-text">
|
| 741 |
-
<strong>Panel Values:</strong> {
|
| 742 |
-
<strong>
|
| 743 |
</div>
|
| 744 |
""",
|
| 745 |
unsafe_allow_html=True,
|
| 746 |
)
|
| 747 |
|
| 748 |
-
# Display total
|
| 749 |
st.write("")
|
| 750 |
st.markdown(
|
| 751 |
f"""
|
| 752 |
<div style="text-align: justify;">
|
| 753 |
-
<strong>Number of
|
| 754 |
-
<strong>Number of Panels detected:</strong> {len(
|
| 755 |
</div>
|
| 756 |
""",
|
| 757 |
unsafe_allow_html=True,
|
|
@@ -766,12 +730,12 @@ with st.expander("Unique DMA and Panel values"):
|
|
| 766 |
|
| 767 |
# Merge all DataFrames selected
|
| 768 |
main_df = create_main_dataframe(
|
| 769 |
-
files_dict,
|
| 770 |
)
|
| 771 |
merged_df = merge_into_main_df(main_df, files_dict, selections)
|
| 772 |
|
| 773 |
# # Display the merged DataFrame
|
| 774 |
-
# st.markdown("#### Merged DataFrame based on selected
|
| 775 |
# st.dataframe(merged_df)
|
| 776 |
|
| 777 |
|
|
@@ -804,7 +768,7 @@ edited_stats_df = st.data_editor(
|
|
| 804 |
"Media",
|
| 805 |
"Exogenous",
|
| 806 |
"Internal",
|
| 807 |
-
"
|
| 808 |
],
|
| 809 |
required=True,
|
| 810 |
default="Media",
|
|
@@ -851,13 +815,12 @@ for i, row in edited_stats_df.iterrows():
|
|
| 851 |
# If it exists, append the current column to the list of variables under this category
|
| 852 |
category_dict[category].append(column)
|
| 853 |
|
| 854 |
-
# Add Date,
|
| 855 |
category_dict.update({"Date": ["date"]})
|
| 856 |
-
if "
|
| 857 |
-
category_dict["
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
category_dict["Panel"] = ["Panel"]
|
| 861 |
|
| 862 |
# Display the dictionary
|
| 863 |
st.markdown("#### Variable Category")
|
|
@@ -879,13 +842,10 @@ for category, variables in category_dict.items():
|
|
| 879 |
# Store final dataframe and bin dictionary into session state
|
| 880 |
st.session_state["final_df"], st.session_state["bin_dict"] = final_df, category_dict
|
| 881 |
|
| 882 |
-
|
| 883 |
-
|
| 884 |
-
|
| 885 |
-
|
| 886 |
-
|
| 887 |
-
|
| 888 |
-
st.
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
|
|
|
| 8 |
initial_sidebar_state="collapsed",
|
| 9 |
)
|
| 10 |
|
| 11 |
+
import pickle
|
| 12 |
import numpy as np
|
| 13 |
import pandas as pd
|
| 14 |
from utilities import set_header, load_local_css, load_authenticator
|
|
|
|
|
|
|
| 15 |
|
| 16 |
load_local_css("styles.css")
|
| 17 |
set_header()
|
|
|
|
| 115 |
|
| 116 |
|
| 117 |
# Function to adjust dataframe granularity
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
def adjust_dataframe_granularity(df, current_granularity, target_granularity):
|
| 119 |
# Set index
|
| 120 |
df.set_index("date", inplace=True)
|
|
|
|
| 174 |
return resampled_df
|
| 175 |
|
| 176 |
|
| 177 |
+
# Function to clean and extract unique values of Panel_1 and Panel_2
|
| 178 |
st.cache_resource(show_spinner=False)
|
| 179 |
|
| 180 |
|
| 181 |
def clean_and_extract_unique_values(files_dict, selections):
|
| 182 |
+
all_panel1_values = set()
|
| 183 |
+
all_panel2_values = set()
|
| 184 |
|
| 185 |
for file_name, file_data in files_dict.items():
|
| 186 |
df = file_data["df"]
|
| 187 |
|
| 188 |
+
# 'Panel_1' and 'Panel_2' selections
|
| 189 |
+
selected_panel1 = selections[file_name].get("Panel_1")
|
| 190 |
+
selected_panel2 = selections[file_name].get("Panel_2")
|
| 191 |
|
| 192 |
+
# Clean and standardize Panel_1 column if it exists and is selected
|
| 193 |
+
if (
|
| 194 |
+
selected_panel1
|
| 195 |
+
and selected_panel1 != "N/A"
|
| 196 |
+
and selected_panel1 in df.columns
|
| 197 |
+
):
|
| 198 |
+
df[selected_panel1] = (
|
| 199 |
+
df[selected_panel1].str.lower().str.strip().str.replace("_", " ")
|
| 200 |
)
|
| 201 |
+
all_panel1_values.update(df[selected_panel1].dropna().unique())
|
| 202 |
|
| 203 |
+
# Clean and standardize Panel_2 column if it exists and is selected
|
| 204 |
+
if (
|
| 205 |
+
selected_panel2
|
| 206 |
+
and selected_panel2 != "N/A"
|
| 207 |
+
and selected_panel2 in df.columns
|
| 208 |
+
):
|
| 209 |
+
df[selected_panel2] = (
|
| 210 |
+
df[selected_panel2].str.lower().str.strip().str.replace("_", " ")
|
| 211 |
)
|
| 212 |
+
all_panel2_values.update(df[selected_panel2].dropna().unique())
|
| 213 |
|
| 214 |
# Update the processed DataFrame back in the dictionary
|
| 215 |
files_dict[file_name]["df"] = df
|
| 216 |
|
| 217 |
+
return all_panel1_values, all_panel2_values
|
| 218 |
|
| 219 |
|
| 220 |
# Function to format values for display
|
|
|
|
| 255 |
for file_name, file_data in files_dict.items():
|
| 256 |
df = file_data["df"].copy()
|
| 257 |
|
| 258 |
+
# Handling when Panel_1 or Panel_2 might be 'N/A'
|
| 259 |
+
selected_panel1 = selections[file_name].get("Panel_1")
|
| 260 |
+
selected_panel2 = selections[file_name].get("Panel_2")
|
| 261 |
|
| 262 |
# Correcting the segment selection logic & handling 'N/A'
|
| 263 |
+
if selected_panel1 != "N/A" and selected_panel2 != "N/A":
|
| 264 |
+
unique_combinations = df[
|
| 265 |
+
[selected_panel1, selected_panel2]
|
| 266 |
+
].drop_duplicates()
|
| 267 |
+
elif selected_panel1 != "N/A":
|
| 268 |
+
unique_combinations = df[[selected_panel1]].drop_duplicates()
|
| 269 |
+
selected_panel2 = None # Ensure Panel_2 is ignored if N/A
|
| 270 |
+
elif selected_panel2 != "N/A":
|
| 271 |
+
unique_combinations = df[[selected_panel2]].drop_duplicates()
|
| 272 |
+
selected_panel1 = None # Ensure Panel_1 is ignored if N/A
|
| 273 |
else:
|
| 274 |
# If both are 'N/A', process the entire dataframe as is
|
| 275 |
df = adjust_dataframe_granularity(
|
|
|
|
| 280 |
|
| 281 |
transformed_segments = []
|
| 282 |
for _, combo in unique_combinations.iterrows():
|
| 283 |
+
if selected_panel1 and selected_panel2:
|
| 284 |
segment = df[
|
| 285 |
+
(df[selected_panel1] == combo[selected_panel1])
|
| 286 |
+
& (df[selected_panel2] == combo[selected_panel2])
|
| 287 |
]
|
| 288 |
+
elif selected_panel1:
|
| 289 |
+
segment = df[df[selected_panel1] == combo[selected_panel1]]
|
| 290 |
+
elif selected_panel2:
|
| 291 |
+
segment = df[df[selected_panel2] == combo[selected_panel2]]
|
| 292 |
|
| 293 |
# Adjust granularity of the segment
|
| 294 |
transformed_segment = adjust_dataframe_granularity(
|
|
|
|
| 308 |
|
| 309 |
|
| 310 |
def create_main_dataframe(
|
| 311 |
+
files_dict, all_panel1_values, all_panel2_values, granularity_selection
|
| 312 |
):
|
| 313 |
# Determine the global start and end dates across all DataFrames
|
| 314 |
global_start = min(df["df"]["date"].min() for df in files_dict.values())
|
|
|
|
| 324 |
else: # Default to daily if not weekly or monthly
|
| 325 |
date_range = pd.date_range(start=global_start, end=global_end, freq="D")
|
| 326 |
|
| 327 |
+
# Collect all unique Panel_1 and Panel_2 values, excluding 'N/A'
|
| 328 |
+
all_panel1s = all_panel1_values
|
| 329 |
+
all_panel2s = all_panel2_values
|
| 330 |
|
| 331 |
+
# Dynamically build the list of dimensions (Panel_1, Panel_2) to include in the main DataFrame based on availability
|
| 332 |
dimensions, merge_keys = [], []
|
| 333 |
+
if all_panel1s:
|
| 334 |
+
dimensions.append(all_panel1s)
|
| 335 |
+
merge_keys.append("Panel_1")
|
| 336 |
+
if all_panel2s:
|
| 337 |
+
dimensions.append(all_panel2s)
|
| 338 |
+
merge_keys.append("Panel_2")
|
| 339 |
|
| 340 |
dimensions.append(date_range) # Date range is always included
|
| 341 |
merge_keys.append("date") # Date range is always included
|
|
|
|
| 357 |
for file_name, file_data in files_dict.items():
|
| 358 |
df = file_data["df"].copy()
|
| 359 |
|
| 360 |
+
# Rename selected Panel_1 and Panel_2 columns if not 'N/A'
|
| 361 |
+
selected_panel1 = selections[file_name].get("Panel_1", "N/A")
|
| 362 |
+
selected_panel2 = selections[file_name].get("Panel_2", "N/A")
|
| 363 |
+
if selected_panel1 != "N/A":
|
| 364 |
+
df.rename(columns={selected_panel1: "Panel_1"}, inplace=True)
|
| 365 |
+
if selected_panel2 != "N/A":
|
| 366 |
+
df.rename(columns={selected_panel2: "Panel_2"}, inplace=True)
|
| 367 |
|
| 368 |
+
# Merge current DataFrame into main_df based on 'date', and where applicable, 'Panel_1' and 'Panel_2'
|
| 369 |
merge_keys = ["date"]
|
| 370 |
+
if "Panel_1" in df.columns:
|
| 371 |
+
merge_keys.append("Panel_1")
|
| 372 |
+
if "Panel_2" in df.columns:
|
| 373 |
+
merge_keys.append("Panel_2")
|
| 374 |
main_df = pd.merge(main_df, df, on=merge_keys, how="left")
|
| 375 |
|
| 376 |
# After all merges, sort by 'date' and reset index for cleanliness
|
| 377 |
sort_by = ["date"]
|
| 378 |
+
if "Panel_1" in main_df.columns:
|
| 379 |
+
sort_by.append("Panel_1")
|
| 380 |
+
if "Panel_2" in main_df.columns:
|
| 381 |
+
sort_by.append("Panel_2")
|
| 382 |
main_df.sort_values(by=sort_by, inplace=True)
|
| 383 |
main_df.reset_index(drop=True, inplace=True)
|
| 384 |
|
|
|
|
| 433 |
missing_stats = []
|
| 434 |
for column in df.columns:
|
| 435 |
if (
|
| 436 |
+
column == "date" or column == "Panel_2" or column == "Panel_1"
|
| 437 |
+
): # Skip Date, Panel_1 and Panel_2 column
|
| 438 |
continue
|
| 439 |
|
| 440 |
missing = df[column].isnull().sum()
|
| 441 |
pct_missing = round((missing / len(df)) * 100, 2)
|
| 442 |
|
| 443 |
# Dynamically assign category based on column name
|
| 444 |
+
category = categorize_column(column)
|
| 445 |
+
# category = "Media" # Keep default bin as Media
|
| 446 |
|
| 447 |
missing_stats.append(
|
| 448 |
{
|
|
|
|
| 482 |
# Function to reads an API into a DataFrame, parsing specified columns as datetime
|
| 483 |
@st.cache_resource(show_spinner=False)
|
| 484 |
def read_API_data():
|
| 485 |
+
return pd.read_excel("upf_data_converted.xlsx", parse_dates=["Date"])
|
| 486 |
|
| 487 |
|
| 488 |
+
# Function to set the 'Panel_1_Panel_2_Selected' session state variable to False
|
| 489 |
+
def set_Panel_1_Panel_2_Selected_false():
|
| 490 |
+
st.session_state["Panel_1_Panel_2_Selected"] = False
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
# Function to serialize and save the objects into a pickle file
|
| 494 |
+
@st.cache_resource(show_spinner=False)
|
| 495 |
+
def save_to_pickle(file_path, final_df, bin_dict):
|
| 496 |
+
# Open the file in write-binary mode and dump the objects
|
| 497 |
+
with open(file_path, "wb") as f:
|
| 498 |
+
pickle.dump({"final_df": final_df, "bin_dict": bin_dict}, f)
|
| 499 |
+
# Data is now saved to file
|
| 500 |
|
| 501 |
|
| 502 |
# Initialize 'final_df' in session state
|
|
|
|
| 507 |
if "bin_dict" not in st.session_state:
|
| 508 |
st.session_state["bin_dict"] = {}
|
| 509 |
|
| 510 |
+
# Initialize 'Panel_1_Panel_2_Selected' in session state
|
| 511 |
+
if "Panel_1_Panel_2_Selected" not in st.session_state:
|
| 512 |
+
st.session_state["Panel_1_Panel_2_Selected"] = False
|
| 513 |
|
| 514 |
# Page Title
|
| 515 |
st.write("") # Top padding
|
|
|
|
| 517 |
|
| 518 |
|
| 519 |
#########################################################################################################################################################
|
| 520 |
+
# Create a dictionary to hold all DataFrames and collect user input to specify "Panel_2" and "Panel_1" columns for each file
|
| 521 |
#########################################################################################################################################################
|
| 522 |
|
| 523 |
|
|
|
|
| 532 |
"Upload additional data",
|
| 533 |
type=["xlsx"],
|
| 534 |
accept_multiple_files=True,
|
| 535 |
+
on_change=set_Panel_1_Panel_2_Selected_false,
|
| 536 |
)
|
| 537 |
|
| 538 |
# Custom HTML for upload instructions
|
| 539 |
recommendation_html = f"""
|
| 540 |
<div style="text-align: justify;">
|
| 541 |
+
<strong>Recommendation:</strong> For optimal processing, please ensure that all uploaded datasets including panel, media, internal, and exogenous data adhere to the following guidelines: Each dataset must include a <code>Date</code> column formatted as <code>DD-MM-YYYY</code>, be free of missing values.
|
| 542 |
</div>
|
| 543 |
"""
|
| 544 |
st.markdown(recommendation_html, unsafe_allow_html=True)
|
| 545 |
|
| 546 |
+
# Choose Desired Granularity
|
| 547 |
+
st.markdown("#### Choose Desired Granularity")
|
| 548 |
# Granularity Selection
|
| 549 |
granularity_selection = st.selectbox(
|
| 550 |
"Choose Date Granularity",
|
| 551 |
["Daily", "Weekly", "Monthly"],
|
| 552 |
label_visibility="collapsed",
|
| 553 |
+
on_change=set_Panel_1_Panel_2_Selected_false,
|
| 554 |
)
|
| 555 |
granularity_selection = str(granularity_selection).lower()
|
| 556 |
|
|
|
|
| 570 |
st.stop() # Halts further execution until file is uploaded
|
| 571 |
|
| 572 |
|
| 573 |
+
# Select Panel_1 and Panel_2 columns
|
| 574 |
+
st.markdown("#### Select Panel columns")
|
| 575 |
selections = {}
|
| 576 |
+
with st.expander("Select Panel columns", expanded=False):
|
| 577 |
count = 0 # Initialize counter to manage the visibility of labels and keys
|
| 578 |
for file_name, file_data in files_dict.items():
|
| 579 |
# Determine visibility of the label based on the count
|
|
|
|
| 585 |
# Extract non-numeric columns
|
| 586 |
non_numeric_cols = file_data["non_numeric"]
|
| 587 |
|
| 588 |
+
# Prepare Panel_1 and Panel_2 values for dropdown, adding "N/A" as an option
|
| 589 |
+
panel1_values = non_numeric_cols + ["N/A"]
|
| 590 |
+
panel2_values = non_numeric_cols + ["N/A"]
|
| 591 |
|
| 592 |
# Skip if only one option is available
|
| 593 |
+
if len(panel1_values) == 1 and len(panel2_values) == 1:
|
| 594 |
+
selected_panel1, selected_panel2 = "N/A", "N/A"
|
| 595 |
+
# Update the selections for Panel_1 and Panel_2 for the current file
|
| 596 |
selections[file_name] = {
|
| 597 |
+
"Panel_1": selected_panel1,
|
| 598 |
+
"Panel_2": selected_panel2,
|
| 599 |
}
|
| 600 |
continue
|
| 601 |
|
| 602 |
+
# Create layout columns for File Name, Panel_2, and Panel_1 selections
|
| 603 |
+
file_name_col, Panel_1_col, Panel_2_col = st.columns([2, 4, 4])
|
| 604 |
|
| 605 |
with file_name_col:
|
| 606 |
# Display "File Name" label only for the first file
|
|
|
|
| 610 |
st.write("")
|
| 611 |
st.write(file_name) # Display the file name
|
| 612 |
|
| 613 |
+
with Panel_1_col:
|
| 614 |
+
# Display a selectbox for Panel_1 values
|
| 615 |
+
selected_panel1 = st.selectbox(
|
| 616 |
+
"Select Panel Level 1",
|
| 617 |
+
panel2_values,
|
| 618 |
+
on_change=set_Panel_1_Panel_2_Selected_false,
|
| 619 |
label_visibility=label_visibility, # Control visibility of the label
|
| 620 |
+
key=f"Panel_1_selectbox{count}", # Ensure unique key for each selectbox
|
| 621 |
)
|
| 622 |
|
| 623 |
+
with Panel_2_col:
|
| 624 |
+
# Display a selectbox for Panel_2 values
|
| 625 |
+
selected_panel2 = st.selectbox(
|
| 626 |
+
"Select Panel Level 2",
|
| 627 |
+
panel1_values,
|
| 628 |
+
on_change=set_Panel_1_Panel_2_Selected_false,
|
| 629 |
label_visibility=label_visibility, # Control visibility of the label
|
| 630 |
+
key=f"Panel_2_selectbox{count}", # Ensure unique key for each selectbox
|
| 631 |
)
|
| 632 |
|
| 633 |
+
# Skip processing if the same column is selected for both Panel_1 and Panel_2 due to potential data integrity issues
|
| 634 |
+
if selected_panel2 == selected_panel1 and not (
|
| 635 |
+
selected_panel2 == "N/A" and selected_panel1 == "N/A"
|
| 636 |
):
|
| 637 |
st.warning(
|
| 638 |
+
f"File: {file_name} → The same column cannot serve as both Panel_1 and Panel_2. Please adjust your selections.",
|
| 639 |
)
|
| 640 |
+
selected_panel1, selected_panel2 = "N/A", "N/A"
|
| 641 |
st.stop()
|
| 642 |
|
| 643 |
+
# Update the selections for Panel_1 and Panel_2 for the current file
|
| 644 |
selections[file_name] = {
|
| 645 |
+
"Panel_1": selected_panel1,
|
| 646 |
+
"Panel_2": selected_panel2,
|
| 647 |
}
|
| 648 |
|
| 649 |
count += 1 # Increment the counter after processing each file
|
| 650 |
|
| 651 |
+
# Accept Panel_1 and Panel_2 selection
|
| 652 |
if st.button("Accept and Process", use_container_width=True):
|
| 653 |
|
| 654 |
# Normalize all data to a daily granularity. This initial standardization simplifies subsequent conversions to other levels of granularity
|
|
|
|
| 661 |
)
|
| 662 |
|
| 663 |
st.session_state["files_dict"] = files_dict
|
| 664 |
+
st.session_state["Panel_1_Panel_2_Selected"] = True
|
| 665 |
|
| 666 |
|
| 667 |
#########################################################################################################################################################
|
| 668 |
+
# Display unique Panel_1 and Panel_2 values
|
| 669 |
#########################################################################################################################################################
|
| 670 |
|
| 671 |
|
| 672 |
+
# Halts further execution until Panel_1 and Panel_2 columns are selected
|
| 673 |
+
if "files_dict" in st.session_state and st.session_state["Panel_1_Panel_2_Selected"]:
|
| 674 |
files_dict = st.session_state["files_dict"]
|
| 675 |
else:
|
| 676 |
st.stop()
|
| 677 |
|
| 678 |
+
# Set to store unique values of Panel_1 and Panel_2
|
| 679 |
+
with st.spinner("Fetching Panel values..."):
|
| 680 |
+
all_panel1_values, all_panel2_values = clean_and_extract_unique_values(
|
| 681 |
files_dict, selections
|
| 682 |
)
|
| 683 |
|
| 684 |
+
# List of Panel_1 and Panel_2 columns unique values
|
| 685 |
+
list_of_all_panel1_values = list(all_panel1_values)
|
| 686 |
+
list_of_all_panel2_values = list(all_panel2_values)
|
| 687 |
|
| 688 |
+
# Format Panel_1 and Panel_2 values for display
|
| 689 |
+
formatted_panel1_values = format_values_for_display(list_of_all_panel1_values)
|
| 690 |
+
formatted_panel2_values = format_values_for_display(list_of_all_panel2_values)
|
| 691 |
|
| 692 |
+
# Unique Panel_1 and Panel_2 values
|
| 693 |
+
st.markdown("#### Unique Panel values")
|
| 694 |
+
# Display Panel_1 and Panel_2 values
|
| 695 |
+
with st.expander("Unique Panel values"):
|
| 696 |
st.write("")
|
| 697 |
st.markdown(
|
| 698 |
f"""
|
|
|
|
| 702 |
}}
|
| 703 |
</style>
|
| 704 |
<div class="justify-text">
|
| 705 |
+
<strong>Panel Level 1 Values:</strong> {formatted_panel1_values}<br>
|
| 706 |
+
<strong>Panel Level 2 Values:</strong> {formatted_panel2_values}
|
| 707 |
</div>
|
| 708 |
""",
|
| 709 |
unsafe_allow_html=True,
|
| 710 |
)
|
| 711 |
|
| 712 |
+
# Display total Panel_1 and Panel_2
|
| 713 |
st.write("")
|
| 714 |
st.markdown(
|
| 715 |
f"""
|
| 716 |
<div style="text-align: justify;">
|
| 717 |
+
<strong>Number of Level 1 Panels detected:</strong> {len(list_of_all_panel1_values)}<br>
|
| 718 |
+
<strong>Number of Level 2 Panels detected:</strong> {len(list_of_all_panel2_values)}
|
| 719 |
</div>
|
| 720 |
""",
|
| 721 |
unsafe_allow_html=True,
|
|
|
|
| 730 |
|
| 731 |
# Merge all DataFrames selected
|
| 732 |
main_df = create_main_dataframe(
|
| 733 |
+
files_dict, all_panel1_values, all_panel2_values, granularity_selection
|
| 734 |
)
|
| 735 |
merged_df = merge_into_main_df(main_df, files_dict, selections)
|
| 736 |
|
| 737 |
# # Display the merged DataFrame
|
| 738 |
+
# st.markdown("#### Merged DataFrame based on selected Panel_1 and Panel_2")
|
| 739 |
# st.dataframe(merged_df)
|
| 740 |
|
| 741 |
|
|
|
|
| 768 |
"Media",
|
| 769 |
"Exogenous",
|
| 770 |
"Internal",
|
| 771 |
+
"Response Metrics",
|
| 772 |
],
|
| 773 |
required=True,
|
| 774 |
default="Media",
|
|
|
|
| 815 |
# If it exists, append the current column to the list of variables under this category
|
| 816 |
category_dict[category].append(column)
|
| 817 |
|
| 818 |
+
# Add Date, Panel_1 and Panel_12 in category dictionary
|
| 819 |
category_dict.update({"Date": ["date"]})
|
| 820 |
+
if "Panel_1" in final_df.columns:
|
| 821 |
+
category_dict["Panel Level 1"] = ["Panel_1"]
|
| 822 |
+
if "Panel_2" in final_df.columns:
|
| 823 |
+
category_dict["Panel Level 2"] = ["Panel_2"]
|
|
|
|
| 824 |
|
| 825 |
# Display the dictionary
|
| 826 |
st.markdown("#### Variable Category")
|
|
|
|
| 842 |
# Store final dataframe and bin dictionary into session state
|
| 843 |
st.session_state["final_df"], st.session_state["bin_dict"] = final_df, category_dict
|
| 844 |
|
| 845 |
+
# Save the DataFrame and dictionary from the session state to the pickle file
|
| 846 |
+
st.write("")
|
| 847 |
+
if st.button("Accept and Save", use_container_width=True):
|
| 848 |
+
save_to_pickle(
|
| 849 |
+
"data_import.pkl", st.session_state["final_df"], st.session_state["bin_dict"]
|
| 850 |
+
)
|
| 851 |
+
st.toast("💾 Saved Successfully!")
|
|
|
|
|
|
|
|
|