Spaces:
Sleeping
Sleeping
File size: 7,134 Bytes
f73646a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | import pandas as pd
import numpy as np
import re
# question understand
def detect_question_type(question: str):
q = question.lower()
patterns = {
"highest": ["highest", "maximum", "max", "most", "top", "best", "largest"],
"lowest": ["lowest", "minimum", "min", "least", "worst", "cheapest", "smallest"],
"average": ["average", "mean", "avg"],
"sum": ["sum", "total", "overall"],
"count": ["count", "how many", "number of", "frequency"],
"correlation": ["correlation", "relationship", "relation", "dependency"],
"distribution": ["distribution", "spread", "breakdown"]
}
for key, words in patterns.items():
if any(w in q for w in words):
return key
return "unknown"
# column match
#def find_matching_columns(question, df):
# q = question.lower()
# matched = []
# for col in df.columns:
# clean_col = col.lower().replace("_", " ")
# direct match
#if clean_col in q:
# matched.append(col)
# continue
# partial token match
#col_tokens = set(clean_col.split())
#q_tokens = set(q.split())
#if len(col_tokens.intersection(q_tokens)) > 0:
# matched.append(col)
# fuzzy keyword match (weak heuristic)
#elif any(token in clean_col for token in q_tokens):
# matched.append(col)
#return list(set(matched))
def find_matching_columns(question, df):
q = question.lower()
scored = []
for col in df.columns:
score = 0
clean = col.lower().replace("_", " ")
# exact
if clean in q:
score += 10
# token overlap
q_words = set(q.split())
c_words = set(clean.split())
overlap = len(q_words.intersection(c_words))
score += overlap * 3
# partial
for w in q_words:
if w in clean:
score += 1
scored.append((col, score))
scored.sort(key=lambda x: x[1], reverse=True)
matched = [
c for c, s in scored
if s > 0
]
return matched[:5]
#########
def get_numeric_columns(df):
return df.select_dtypes(include=["int64", "float64"]).columns.tolist()
def get_categorical_columns(df):
return df.select_dtypes(include=["object", "category"]).columns.tolist()
def pick_best_group_and_value(df, matched_cols):
numeric = [c for c in matched_cols if c in get_numeric_columns(df)]
cat = [c for c in matched_cols if c in get_categorical_columns(df)]
if not numeric:
numeric = get_numeric_columns(df)
if not cat:
cat = get_categorical_columns(df)
if not numeric or not cat:
return None, None
return cat[0], numeric[0]
# high & low
def handle_groupby_question(df, matched_cols, qtype):
group_col, value_col = pick_best_group_and_value(df, matched_cols)
if not group_col or not value_col:
return "Not enough data to compute group analysis."
try:
grouped = (
df.groupby(group_col)[value_col]
.mean()
.sort_values(ascending=(qtype == "lowest"))
)
top = grouped.head(1)
name = top.index[0]
value = top.values[0]
label = "highest" if qtype == "highest" else "lowest"
return (
f"'{name}' has the {label} average {value_col}: "
f"{value:.2f}."
)
except Exception as e:
return f"Group analysis failed: {e}"
# avg , mean , sum , median
def handle_numeric_stats(df, matched_cols, mode="average"):
numeric_cols = [c for c in matched_cols if c in get_numeric_columns(df)]
if not numeric_cols:
numeric_cols = get_numeric_columns(df)
if not numeric_cols:
return "No numeric columns found."
col = numeric_cols[0]
try:
if mode == "average":
val = df[col].mean()
elif mode == "sum":
val = df[col].sum()
elif mode == "median":
val = df[col].median()
else:
val = df[col].mean()
return f"{mode.title()} of '{col}' is {val:.2f}"
except Exception as e:
return f"Error calculating {mode}: {e}"
# count , number of
def handle_count_question(df, matched_cols):
if not matched_cols:
return f"Dataset contains {len(df)} rows."
col = matched_cols[0]
try:
counts = df[col].value_counts().head(10)
result = f"Top values in '{col}':\n"
for k, v in counts.items():
result += f"- {k}: {v}\n"
return result
except Exception as e:
return f"Count error: {e}"
# correlation , relationship
def handle_correlation_question(df, matched_cols):
numeric_cols = [c for c in matched_cols if c in get_numeric_columns(df)]
if len(numeric_cols) < 2:
numeric_cols = get_numeric_columns(df)
if len(numeric_cols) < 2:
return "Need at least 2 numeric columns for correlation."
best_pairs = []
# compute best correlation pairs
for i in range(len(numeric_cols)):
for j in range(i + 1, len(numeric_cols)):
c1, c2 = numeric_cols[i], numeric_cols[j]
corr = df[c1].corr(df[c2])
if pd.notna(corr):
best_pairs.append((abs(corr), c1, c2, corr))
if not best_pairs:
return "No correlation found."
best_pairs.sort(reverse=True)
_, c1, c2, corr = best_pairs[0]
strength = "weak"
if abs(corr) > 0.7:
strength = "strong"
elif abs(corr) > 0.4:
strength = "moderate"
direction = "positive" if corr > 0 else "negative"
return (
f"Strongest correlation is between '{c1}' and '{c2}': "
f"{corr:.3f} ({strength} {direction})."
)
##### main
def answer_data_question(df, question):
if not question or not question.strip():
return "Please enter a valid question."
qtype = detect_question_type(question)
matched_cols = find_matching_columns(question, df)
# HIGH / LOW
if qtype in ["highest", "lowest"]:
return handle_groupby_question(df, matched_cols, qtype)
# AVERAGE
elif qtype == "average":
return handle_numeric_stats(df, matched_cols, "average")
# SUM
elif qtype == "sum":
return handle_numeric_stats(df, matched_cols, "sum")
# COUNT
elif qtype == "count":
return handle_count_question(df, matched_cols)
# CORRELATION
elif qtype == "correlation":
return handle_correlation_question(df, matched_cols)
# UNKNOWN → fallback intelligent response
else:
return (
"I couldn't fully understand the question. "
"Try asking about averages, highest/lowest values, counts, or relationships."
) |