Untitled

 avatar
unknown
plain_text
10 months ago
1.4 kB
15
Indexable
import numpy as np
import os

# ensure analytics_df is not empty and has the column
if 'subscribersGained' not in analytics_df.columns:
    raise KeyError("analytics_df must contain 'subscribersGained' column")

# convert to numeric and fill NaN with 0
analytics_df['subscribersGained'] = pd.to_numeric(analytics_df['subscribersGained'], errors='coerce').fillna(0)

# basic stats
mean = analytics_df['subscribersGained'].mean()
std = analytics_df['subscribersGained'].std(ddof=0)  # population std; change if you want sample std

# avoid divide-by-zero; if std==0 set denom to 1 (no variation)
denom = std if std > 0 else 1.0
analytics_df['zscore'] = (analytics_df['subscribersGained'] - mean) / denom

# percent change vs previous day
analytics_df['pct_change'] = analytics_df['subscribersGained'].pct_change().replace([np.inf, -np.inf], np.nan).fillna(0)

# thresholds (tune as needed)
threshold_z = 3.0        # z-score threshold
threshold_pct = 1.0      # 1.0 == 100% increase relative to previous day

# flag suspicious rows
suspicious = analytics_df[(analytics_df['zscore'] > threshold_z) | (analytics_df['pct_change'] > threshold_pct)].copy()

print("Suspicious rows:\n", suspicious)

# save outputs (ensure out_dir exists)
os.makedirs(out_dir, exist_ok=True)
suspicious.to_csv(os.path.join(out_dir, "suspicious_subscriber_spikes.csv"), index=False)
Editor is loading...
Leave a Comment