Spaces:
Sleeping
Sleeping
SimHS98 commited on
Commit ·
bd7bb75
1
Parent(s): 0e901ac
269 unmodified lines2702712722732742752762772782792802812822831 unmodified line2852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403414 unmodified lines346347348349350351352353354355356357358359360361362363364365366367368369370371269 unmodified linesdef transform_to_standard_format(df):"""3단계 멀티헤더 구조 기반 표준화- 1행: Country (SG, MY, ...)- 2행: Type (매출, 지출)- 3행: Channel (쇼피파이, Meta, 내부 광고 등)- (KRW) 포함 여부로 Amount_KRW/Amount_Local 구분- ISO 통화코드 자동 설정- OrderID, SKU/ASIN, Units 등 원본 필드 유지"""if df.empty:return pd.DataFrame(), pd.DataFrame()1 unmodified linedf.rename(columns={df.columns[0]: "Date"}, inplace=True)df["Date"] = pd.to_datetime(df["Date"], errors="coerce")# 보조 컬럼 (있으면 유지)base_cols = [c for c in ["OrderID", "SKU/ASIN", "SKU", "ASIN", "Units"] if c in df.columns]melt_cols = [c for c in df.columns if c not in ["Date"] + base_cols]records = []# 2️⃣ 컬럼 파싱 및 값 전개for col in melt_cols:parts = col.split("_")if len(parts) == 3:country, dtype, channel = partselif len(parts) == 2:country, dtype = partschannel = "Total"else:continue# 매출 / 지출만 처리if dtype not in ["매출", "지출"]:continuefor idx, val in enumerate(df[col]):if val not in [None, "", " ", "-", 0]:record = {"Date": df.loc[idx, "Date"],"Country": country.strip(),"Type": dtype.strip(),"Channel": channel.strip(),"Value": val}for base in base_cols:record[base] = df.loc[idx, base] if base in df.columns else Nonerecords.append(record)df_flat = pd.DataFrame(records)# 3️⃣ ISO 통화코드 매핑currency_map = {"SG": "SGD", "MY": "MYR", "PH": "PHP","TW": "TWD", "TH": "THB", "VN": "VND","US": "USD", "KR": "KRW"}df_flat["Currency"] = df_flat["Country"].map(currency_map).fillna("Local")# 4️⃣ (KRW) 포함 여부로 금액 분리df_flat["Amount_Local"] = df_flat.apply(lambda x: x["Value"] if "(KRW)" not in x["Channel"] else None, axis=1)df_flat["Amount_KRW"] = df_flat.apply(lambda x: x["Value"] if "(KRW)" in x["Channel"] else None, axis=1)# 5️⃣ Sales / Ads 분리4 unmodified linesdf_sales = df_sales[df_sales["Amount_KRW"].notnull() & (df_sales["Amount_KRW"] != 0)]df_ads = df_ads[df_ads["Amount_KRW"].notnull() & (df_ads["Amount_KRW"] != 0)]# 7️⃣ 컬럼 순서 정리 (결측 컬럼 안전 처리)# 누락 컬럼 보정for col in ["OrderID", "SKU", "ASIN", "Units"]:if col not in df_sales.columns:df_sales[col] = ""if col not in df_ads.columns and col != "Units": # Ads엔 Units 없음df_ads[col] = ""# Sales 컬럼 순서df_sales = df_sales[["Date", "Country", "Channel", "OrderID", "SKU", "ASIN", "Units","Amount_Local", "Currency", "Amount_KRW"]]# Ads 컬럼 순서df_ads["Campaign"] = ""df_ads = df_ads[["Date", "Country", "Channel", "Campaign","Amount_Local", "Currency", "Amount_KRW"]]return df_sales, df_ads269 unmodified lines2702712722732742752762772782792801 unmodified line2822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263274 unmodified lines332333334335336337338339340341342343344345346347348349350351352353354355356357358359269 unmodified linesdef transform_to_standard_format(df):"""3단계 멀티헤더 구조 기반 표준화- 헤더 예: 쇼피파이(KRW), 쇼피파이(SGD), 쇼피파이(Units)- (KRW): 원화, 다른 통화: 현지 통화, (Units): 수량- OrderID, SKU/ASIN, Units 등 원본 필드 유지- Amount_KRW == 0 or None 제외"""if df.empty:return pd.DataFrame(), pd.DataFrame()1 unmodified linedf.rename(columns={df.columns[0]: "Date"}, inplace=True)df["Date"] = pd.to_datetime(df["Date"], errors="coerce")base_cols = [c for c in ["OrderID", "SKU/ASIN", "SKU", "ASIN"] if c in df.columns]melt_cols = [c for c in df.columns if c not in ["Date"] + base_cols]records = []# 2️⃣ 컬럼 파싱for col in melt_cols:parts = col.split("_")if len(parts) < 3:continuecountry, dtype, channel = parts[0], parts[1], parts[2]if dtype not in ["매출", "지출"]:continuefor idx, val in enumerate(df[col]):if val not in [None, "", " ", "-", 0]:records.append({"Date": df.loc[idx, "Date"],"Country": country.strip(),"Type": dtype.strip(),"Channel": channel.strip(),"Value": val})df_flat = pd.DataFrame(records)# 3️⃣ Channel 분해 (예: 쇼피파이(KRW) → 이름 + 통화)channel_info = df_flat["Channel"].str.extract(r"(?P<Name>.+)\((?P<Currency>.+)\)")df_flat["ChannelName"] = channel_info["Name"].str.strip()df_flat["Currency"] = channel_info["Currency"].fillna("Local")# 4️⃣ Amount 구분df_flat["Amount_KRW"] = df_flat.apply(lambda x: x["Value"] if x["Currency"] == "KRW" else None, axis=1)df_flat["Amount_Local"] = df_flat.apply(lambda x: x["Value"] if x["Currency"] != "KRW" and x["Currency"] != "Units" else None, axis=1)df_flat["Units"] = df_flat.apply(lambda x: x["Value"] if x["Currency"].lower() == "units" else None, axis=1)# 5️⃣ Sales / Ads 분리4 unmodified linesdf_sales = df_sales[df_sales["Amount_KRW"].notnull() & (df_sales["Amount_KRW"] != 0)]df_ads = df_ads[df_ads["Amount_KRW"].notnull() & (df_ads["Amount_KRW"] != 0)]# 7️⃣ 컬럼 정리for col in ["OrderID", "SKU", "ASIN"]:if col not in df_sales.columns:df_sales[col] = Noneif col not in df_ads.columns:df_ads[col] = None# 8️⃣ 컬럼 순서 맞추기df_sales = df_sales[["Date", "Country", "ChannelName", "OrderID", "SKU", "ASIN", "Units","Amount_Local", "Currency", "Amount_KRW"]]df_ads["Campaign"] = ""df_ads = df_ads[["Date", "Country", "ChannelName", "Campaign","Amount_Local", "Currency", "Amount_KRW"]]# 9️⃣ ChannelName → Channel로 리네임df_sales.rename(columns={"ChannelName": "Channel"}, inplace=True)df_ads.rename(columns={"ChannelName": "Channel"}, inplace=True)return df_sales, df_ads
main.py+35-47