codebuff-agent 2.1.74__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codebuff_agent-2.1.74.data/data/etc/jupyter/jupyter_server_config.d/codebuff_agent.json +7 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/package.json +157 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/104.2b8f20f9d1ac2c9db01b.js +1 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/150.39fa98117cc8ca590465.js +1 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/166.386ff9b2c37ac865fdee.js +1 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/216.25cf81131bf7274dabf4.js +1 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/353.581bd1cb00746399b62e.js +1 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/367.575f9621b63c9a641aa9.js +1 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/421.11dac223a2c2da1b09f5.js +1 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/432.8513b4c6cc1d1232d165.js +2 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/432.8513b4c6cc1d1232d165.js.LICENSE.txt +19 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/439.ba5b5ef70ec6de214b8c.js +2 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/439.ba5b5ef70ec6de214b8c.js.LICENSE.txt +8 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/481.cc2dec9fa869d66f1407.js +1 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/487.0796e931d6e651482c14.js +1 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/49.d326f554b6f9ccde6580.js +1 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/541.26897ea32845659e36be.js +1 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/579.e569d3edd8391fd8fbb3.js +1 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/58.eb7cc679f7535cc8a2f1.js +2 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/58.eb7cc679f7535cc8a2f1.js.LICENSE.txt +8 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/666.d9bfdb23f98489d0a188.js +1 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/677.d266c39dbed33bc388b3.js +2 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/677.d266c39dbed33bc388b3.js.LICENSE.txt +8 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/68.26b6f59c8454adb17f20.js +204 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/694.4ac443814260057e68f7.js +1 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/791.61affb8d3480d3d60e0d.js +1 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/848.4d2db09cfbb09374b299.js +2 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/848.4d2db09cfbb09374b299.js.LICENSE.txt +9 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/868.5cfe7e1a348ec5af1b8c.js +1 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/97.ea559a5b8a9a09f17c6b.js +1 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/remoteEntry.5292fc9c6df7e7920cc8.js +1 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/style.js +4 -0
- codebuff_agent-2.1.74.data/data/share/jupyter/labextensions/codebuff/static/third-party-licenses.json +724 -0
- codebuff_agent-2.1.74.dist-info/METADATA +142 -0
- codebuff_agent-2.1.74.dist-info/RECORD +217 -0
- codebuff_agent-2.1.74.dist-info/WHEEL +4 -0
- codebuff_agent-2.1.74.dist-info/licenses/LICENSE +21 -0
- codebuff_core/__init__.py +153 -0
- codebuff_core/codebuff_config_defaults.json +64 -0
- codebuff_core/core/__init__.py +35 -0
- codebuff_core/core/code_validator.py +1238 -0
- codebuff_core/core/error_classifier.py +579 -0
- codebuff_core/core/exceptions.py +49 -0
- codebuff_core/data/tiktoken_cache/9b5ad71b2ce5302211f9c61530b329a4922fc6a4 +100256 -0
- codebuff_core/directory_policy.py +32 -0
- codebuff_core/factory.py +155 -0
- codebuff_core/interfaces.py +197 -0
- codebuff_core/knowledge/__init__.py +31 -0
- codebuff_core/knowledge/chunking.py +375 -0
- codebuff_core/knowledge/loader.py +339 -0
- codebuff_core/knowledge/watchdog_service.py +354 -0
- codebuff_core/legacy_paths.py +69 -0
- codebuff_core/llm/__init__.py +13 -0
- codebuff_core/llm/service.py +407 -0
- codebuff_core/managers/__init__.py +22 -0
- codebuff_core/managers/config_manager.py +690 -0
- codebuff_core/managers/remote_config.py +673 -0
- codebuff_core/managers/remote_skills.py +539 -0
- codebuff_core/managers/session_manager.py +255 -0
- codebuff_core/middleware/__init__.py +3 -0
- codebuff_core/middleware/error_recovery.py +394 -0
- codebuff_core/middleware/logging_utils.py +33 -0
- codebuff_core/models/__init__.py +111 -0
- codebuff_core/models/agent.py +306 -0
- codebuff_core/models/chat.py +57 -0
- codebuff_core/models/common.py +82 -0
- codebuff_core/models/rag.py +300 -0
- codebuff_core/platform_rules.py +127 -0
- codebuff_core/prompts/__init__.py +44 -0
- codebuff_core/prompts/auto_agent_prompts.py +1278 -0
- codebuff_core/services/__init__.py +30 -0
- codebuff_core/services/agent_service.py +345 -0
- codebuff_core/services/analytics_aggregate.py +837 -0
- codebuff_core/services/chat_service.py +898 -0
- codebuff_core/services/context_condenser.py +306 -0
- codebuff_core/services/pii_guardrail.py +393 -0
- codebuff_core/services/rag_chat_agent.py +2993 -0
- codebuff_core/services/rag_collections.py +2740 -0
- codebuff_core/services/rag_manager.py +890 -0
- codebuff_core/services/rag_service.py +145 -0
- codebuff_core/services/retriever.py +260 -0
- codebuff_core/services/vllm_embedding_service.py +290 -0
- codebuff_core/tests/__init__.py +1 -0
- codebuff_core/tests/conftest.py +81 -0
- codebuff_core/tests/test_error_recovery.py +647 -0
- codebuff_core/tests/test_factory.py +135 -0
- codebuff_core/tests/test_services.py +150 -0
- jupyter_ext/__init__.py +266 -0
- jupyter_ext/_version.py +4 -0
- jupyter_ext/agent/__init__.py +49 -0
- jupyter_ext/agent/agent_factory.py +2270 -0
- jupyter_ext/agent/ast_tools.py +451 -0
- jupyter_ext/agent/autofix_middleware.py +481 -0
- jupyter_ext/agent/background_procs.py +372 -0
- jupyter_ext/agent/code_history_middleware.py +211 -0
- jupyter_ext/agent/codex_autofix.py +160 -0
- jupyter_ext/agent/codex_bridge.py +3339 -0
- jupyter_ext/agent/codex_hooks.py +320 -0
- jupyter_ext/agent/codex_slash.py +685 -0
- jupyter_ext/agent/codex_threads.py +114 -0
- jupyter_ext/agent/content_injection.py +377 -0
- jupyter_ext/agent/continuation_middleware.py +548 -0
- jupyter_ext/agent/custom_skills.py +335 -0
- jupyter_ext/agent/file_diffs.py +99 -0
- jupyter_ext/agent/git_history.py +188 -0
- jupyter_ext/agent/guardrail_middleware.py +421 -0
- jupyter_ext/agent/json_repair_utils.py +54 -0
- jupyter_ext/agent/langchain_tools.py +2673 -0
- jupyter_ext/agent/mermaid_fixer.py +289 -0
- jupyter_ext/agent/mermaid_middleware.py +135 -0
- jupyter_ext/agent/middleware.py +359 -0
- jupyter_ext/agent/middleware_prompts.py +53 -0
- jupyter_ext/agent/observability.py +334 -0
- jupyter_ext/agent/patch_tool_calls.py +57 -0
- jupyter_ext/agent/prompts.py +112 -0
- jupyter_ext/agent/skill_middleware.py +257 -0
- jupyter_ext/agent/skills/airflow_dag_development.md +36 -0
- jupyter_ext/agent/skills/anomaly_detection.md +12 -0
- jupyter_ext/agent/skills/athena_sql.md +156 -0
- jupyter_ext/agent/skills/bdp_table_search.md +33 -0
- jupyter_ext/agent/skills/bigquery.md +65 -0
- jupyter_ext/agent/skills/bigquery_oracle.md +231 -0
- jupyter_ext/agent/skills/bigquery_tuning.md +307 -0
- jupyter_ext/agent/skills/classification_evaluation.md +11 -0
- jupyter_ext/agent/skills/clustering_analysis.md +12 -0
- jupyter_ext/agent/skills/comprehensive_eda.md +11 -0
- jupyter_ext/agent/skills/data_analysis.md +236 -0
- jupyter_ext/agent/skills/data_cleaning_pipeline.md +12 -0
- jupyter_ext/agent/skills/data_loading.md +158 -0
- jupyter_ext/agent/skills/data_quality_report.md +13 -0
- jupyter_ext/agent/skills/dimensionality_reduction.md +12 -0
- jupyter_ext/agent/skills/emr_script_development.md +17 -0
- jupyter_ext/agent/skills/experiment_tracking.md +13 -0
- jupyter_ext/agent/skills/feature_importance_analysis.md +10 -0
- jupyter_ext/agent/skills/hyperparameter_tuning.md +12 -0
- jupyter_ext/agent/skills/hypothesis_testing.md +12 -0
- jupyter_ext/agent/skills/imbalanced_data_handling.md +12 -0
- jupyter_ext/agent/skills/inference.md +392 -0
- jupyter_ext/agent/skills/lambda_function_development.md +19 -0
- jupyter_ext/agent/skills/model_comparison.md +11 -0
- jupyter_ext/agent/skills/model_explainability.md +12 -0
- jupyter_ext/agent/skills/model_training.md +318 -0
- jupyter_ext/agent/skills/pyspark.md +352 -0
- jupyter_ext/agent/skills/python_code_quality.md +35 -0
- jupyter_ext/agent/skills/regression_evaluation.md +12 -0
- jupyter_ext/agent/skills/spring_java_development.md +35 -0
- jupyter_ext/agent/skills/text_preprocessing.md +12 -0
- jupyter_ext/agent/skills/time_series_analysis.md +13 -0
- jupyter_ext/agent/skills/unit_testing.md +203 -0
- jupyter_ext/agent/todo_prompts.py +57 -0
- jupyter_ext/agent/tool_report.py +45 -0
- jupyter_ext/analytics_ingest.py +599 -0
- jupyter_ext/etc/jupyter/jupyter_server_config.d/codebuff_agent.json +7 -0
- jupyter_ext/handlers/__init__.py +8 -0
- jupyter_ext/handlers/analytics_handler.py +170 -0
- jupyter_ext/handlers/benchmark_handler.py +794 -0
- jupyter_ext/handlers/eda_benchmark_handler.py +1328 -0
- jupyter_ext/handlers/rag_admin_handler.py +689 -0
- jupyter_ext/handlers/websocket.py +497 -0
- jupyter_ext/http_handlers.py +8744 -0
- jupyter_ext/idle_monitor.py +346 -0
- jupyter_ext/labextension/package.json +157 -0
- jupyter_ext/labextension/static/104.2b8f20f9d1ac2c9db01b.js +1 -0
- jupyter_ext/labextension/static/150.39fa98117cc8ca590465.js +1 -0
- jupyter_ext/labextension/static/166.386ff9b2c37ac865fdee.js +1 -0
- jupyter_ext/labextension/static/216.25cf81131bf7274dabf4.js +1 -0
- jupyter_ext/labextension/static/353.581bd1cb00746399b62e.js +1 -0
- jupyter_ext/labextension/static/367.575f9621b63c9a641aa9.js +1 -0
- jupyter_ext/labextension/static/421.11dac223a2c2da1b09f5.js +1 -0
- jupyter_ext/labextension/static/432.8513b4c6cc1d1232d165.js +2 -0
- jupyter_ext/labextension/static/432.8513b4c6cc1d1232d165.js.LICENSE.txt +19 -0
- jupyter_ext/labextension/static/439.ba5b5ef70ec6de214b8c.js +2 -0
- jupyter_ext/labextension/static/439.ba5b5ef70ec6de214b8c.js.LICENSE.txt +8 -0
- jupyter_ext/labextension/static/481.cc2dec9fa869d66f1407.js +1 -0
- jupyter_ext/labextension/static/487.0796e931d6e651482c14.js +1 -0
- jupyter_ext/labextension/static/49.d326f554b6f9ccde6580.js +1 -0
- jupyter_ext/labextension/static/541.26897ea32845659e36be.js +1 -0
- jupyter_ext/labextension/static/579.e569d3edd8391fd8fbb3.js +1 -0
- jupyter_ext/labextension/static/58.eb7cc679f7535cc8a2f1.js +2 -0
- jupyter_ext/labextension/static/58.eb7cc679f7535cc8a2f1.js.LICENSE.txt +8 -0
- jupyter_ext/labextension/static/666.d9bfdb23f98489d0a188.js +1 -0
- jupyter_ext/labextension/static/677.d266c39dbed33bc388b3.js +2 -0
- jupyter_ext/labextension/static/677.d266c39dbed33bc388b3.js.LICENSE.txt +8 -0
- jupyter_ext/labextension/static/68.26b6f59c8454adb17f20.js +204 -0
- jupyter_ext/labextension/static/694.4ac443814260057e68f7.js +1 -0
- jupyter_ext/labextension/static/791.61affb8d3480d3d60e0d.js +1 -0
- jupyter_ext/labextension/static/848.4d2db09cfbb09374b299.js +2 -0
- jupyter_ext/labextension/static/848.4d2db09cfbb09374b299.js.LICENSE.txt +9 -0
- jupyter_ext/labextension/static/868.5cfe7e1a348ec5af1b8c.js +1 -0
- jupyter_ext/labextension/static/97.ea559a5b8a9a09f17c6b.js +1 -0
- jupyter_ext/labextension/static/remoteEntry.5292fc9c6df7e7920cc8.js +1 -0
- jupyter_ext/labextension/static/style.js +4 -0
- jupyter_ext/labextension/static/third-party-licenses.json +724 -0
- jupyter_ext/log_paths.py +113 -0
- jupyter_ext/resource_usage.py +519 -0
- jupyter_ext/secrets_bootstrap.py +116 -0
- jupyter_ext/team_access.py +105 -0
- jupyter_ext/tests/__init__.py +1 -0
- jupyter_ext/tests/test_context.py +234 -0
- jupyter_ext/tests/test_factory.py +563 -0
- jupyter_ext/tests/test_file_finder.py +139 -0
- jupyter_ext/tests/test_handlers.py +58 -0
- jupyter_ext/tests/test_mcp_selftest.py +204 -0
- jupyter_ext/tests/test_mermaid_fixer.py +272 -0
- jupyter_ext/tests/test_resource_tiers.py +298 -0
- jupyter_ext/tools/__init__.py +15 -0
- jupyter_ext/tools/base.py +90 -0
- jupyter_ext/tools/context.py +268 -0
- jupyter_ext/tools/dir_complete.py +86 -0
- jupyter_ext/tools/file_finder.py +303 -0
- jupyter_ext/tools/file_tools.py +244 -0
- jupyter_ext/tools/jupyter_tools.py +296 -0
- jupyter_ext/tools/registry.py +159 -0
- jupyter_ext/tools/search_tools.py +230 -0
- jupyter_ext/tools/security_tools.py +657 -0
- jupyter_ext/tools/shell_tools.py +109 -0
- jupyter_ext/tools/user_tools.py +132 -0
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: data-analysis
|
|
3
|
+
description: DataFrame 연산 최적화. 행 수가 100만 이상이거나 groupby, merge, pivot 등 메모리 집약적 연산 시 사용. 벡터화 연산, query 최적화, 메모리 효율적 패턴 제공.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Data Analysis Optimization Guide
|
|
7
|
+
|
|
8
|
+
pandas DataFrame의 분석 연산을 메모리 효율적으로 수행하는 방법을 안내합니다.
|
|
9
|
+
|
|
10
|
+
## Resource Tiers
|
|
11
|
+
|
|
12
|
+
### TIER_SMALL: DataFrame < 1GB, RAM 여유 충분
|
|
13
|
+
일반 pandas 연산 OK.
|
|
14
|
+
|
|
15
|
+
### TIER_MEDIUM: DataFrame 1~5GB
|
|
16
|
+
벡터화 연산 + query 최적화 필수
|
|
17
|
+
|
|
18
|
+
### TIER_LARGE: DataFrame > 5GB 또는 메모리 부족
|
|
19
|
+
Dask/Polars 사용 또는 청크 처리
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## 1. 벡터화 연산 (Vectorization)
|
|
24
|
+
|
|
25
|
+
### 나쁜 예: 반복문 사용
|
|
26
|
+
```python
|
|
27
|
+
# 느림 - 절대 사용 금지
|
|
28
|
+
for i in range(len(df)):
|
|
29
|
+
df.loc[i, "new_col"] = df.loc[i, "col1"] * 2
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### 좋은 예: 벡터화
|
|
33
|
+
```python
|
|
34
|
+
# 빠름 - 항상 이 방법 사용
|
|
35
|
+
df["new_col"] = df["col1"] * 2
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### 조건부 연산
|
|
39
|
+
```python
|
|
40
|
+
# 나쁜 예: apply 사용
|
|
41
|
+
df["category"] = df["value"].apply(lambda x: "high" if x > 100 else "low")
|
|
42
|
+
|
|
43
|
+
# 좋은 예: np.where 사용 (10x+ 빠름)
|
|
44
|
+
import numpy as np
|
|
45
|
+
df["category"] = np.where(df["value"] > 100, "high", "low")
|
|
46
|
+
|
|
47
|
+
# 여러 조건: np.select 사용
|
|
48
|
+
conditions = [
|
|
49
|
+
df["value"] > 100,
|
|
50
|
+
df["value"] > 50,
|
|
51
|
+
]
|
|
52
|
+
choices = ["high", "medium"]
|
|
53
|
+
df["category"] = np.select(conditions, choices, default="low")
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## 2. GroupBy 최적화
|
|
59
|
+
|
|
60
|
+
### 기본 최적화
|
|
61
|
+
```python
|
|
62
|
+
# sort=False로 정렬 비용 제거
|
|
63
|
+
result = df.groupby("category", sort=False)["value"].sum()
|
|
64
|
+
|
|
65
|
+
# 여러 집계 한 번에
|
|
66
|
+
result = df.groupby("category", sort=False).agg({
|
|
67
|
+
"value": ["sum", "mean", "count"],
|
|
68
|
+
"amount": "sum"
|
|
69
|
+
})
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### 대용량 GroupBy (메모리 부족 시)
|
|
73
|
+
```python
|
|
74
|
+
# Option A: numba 가속 (설치 필요)
|
|
75
|
+
@numba.jit
|
|
76
|
+
def custom_agg(values):
|
|
77
|
+
return values.sum()
|
|
78
|
+
|
|
79
|
+
result = df.groupby("category")["value"].agg(custom_agg)
|
|
80
|
+
|
|
81
|
+
# Option B: Dask 사용
|
|
82
|
+
import dask.dataframe as dd
|
|
83
|
+
ddf = dd.from_pandas(df, npartitions=4)
|
|
84
|
+
result = ddf.groupby("category")["value"].sum().compute()
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## 3. Merge/Join 최적화
|
|
90
|
+
|
|
91
|
+
### 메모리 효율적 Merge
|
|
92
|
+
```python
|
|
93
|
+
# 1. 필요한 컬럼만 선택 후 merge
|
|
94
|
+
df1_subset = df1[["key", "needed_col1", "needed_col2"]]
|
|
95
|
+
df2_subset = df2[["key", "needed_col3"]]
|
|
96
|
+
result = pd.merge(df1_subset, df2_subset, on="key")
|
|
97
|
+
|
|
98
|
+
# 2. 작은 테이블을 왼쪽에 배치 (메모리 효율)
|
|
99
|
+
result = pd.merge(small_df, large_df, on="key", how="left")
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### 대용량 Merge (메모리 부족 시)
|
|
103
|
+
```python
|
|
104
|
+
# Chunked merge
|
|
105
|
+
def chunked_merge(large_df, small_df, on, chunksize=100_000):
|
|
106
|
+
chunks = []
|
|
107
|
+
for start in range(0, len(large_df), chunksize):
|
|
108
|
+
chunk = large_df.iloc[start:start + chunksize]
|
|
109
|
+
merged = pd.merge(chunk, small_df, on=on, how="left")
|
|
110
|
+
chunks.append(merged)
|
|
111
|
+
return pd.concat(chunks, ignore_index=True)
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
## 4. Query 최적화
|
|
117
|
+
|
|
118
|
+
### eval() 사용 (대용량 DataFrame에서 빠름)
|
|
119
|
+
```python
|
|
120
|
+
# 일반 방식
|
|
121
|
+
df["c"] = df["a"] + df["b"]
|
|
122
|
+
df["d"] = df["c"] * 2
|
|
123
|
+
|
|
124
|
+
# eval() 사용 (중간 결과 메모리 절약)
|
|
125
|
+
df = df.eval("""
|
|
126
|
+
c = a + b
|
|
127
|
+
d = c * 2
|
|
128
|
+
""")
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### query() 사용 (필터링)
|
|
132
|
+
```python
|
|
133
|
+
# 일반 방식
|
|
134
|
+
result = df[(df["col1"] > 10) & (df["col2"] == "active")]
|
|
135
|
+
|
|
136
|
+
# query() 사용 (더 빠르고 가독성 좋음)
|
|
137
|
+
result = df.query("col1 > 10 and col2 == 'active'")
|
|
138
|
+
|
|
139
|
+
# 변수 사용
|
|
140
|
+
threshold = 10
|
|
141
|
+
status = "active"
|
|
142
|
+
result = df.query("col1 > @threshold and col2 == @status")
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
---
|
|
146
|
+
|
|
147
|
+
## 5. 피벗/언피벗 최적화
|
|
148
|
+
|
|
149
|
+
### Pivot Table
|
|
150
|
+
```python
|
|
151
|
+
# 기본 사용
|
|
152
|
+
pivot = df.pivot_table(
|
|
153
|
+
values="amount",
|
|
154
|
+
index="date",
|
|
155
|
+
columns="category",
|
|
156
|
+
aggfunc="sum",
|
|
157
|
+
fill_value=0
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
# 메모리 부족 시: 청크로 처리
|
|
161
|
+
def chunked_pivot(df, chunksize=100_000):
|
|
162
|
+
results = []
|
|
163
|
+
for start in range(0, len(df), chunksize):
|
|
164
|
+
chunk = df.iloc[start:start + chunksize]
|
|
165
|
+
pivot = chunk.pivot_table(...)
|
|
166
|
+
results.append(pivot)
|
|
167
|
+
return pd.concat(results).groupby(level=0).sum()
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
---
|
|
171
|
+
|
|
172
|
+
## 6. 메모리 관리
|
|
173
|
+
|
|
174
|
+
### 불필요한 객체 삭제
|
|
175
|
+
```python
|
|
176
|
+
import gc
|
|
177
|
+
|
|
178
|
+
# 중간 결과 삭제
|
|
179
|
+
del intermediate_df
|
|
180
|
+
gc.collect()
|
|
181
|
+
|
|
182
|
+
# 컬럼 삭제 (inplace)
|
|
183
|
+
df.drop(columns=["unneeded_col"], inplace=True)
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
### 원본 유지하면서 메모리 절약
|
|
187
|
+
```python
|
|
188
|
+
# 복사 대신 view 사용 (가능할 때)
|
|
189
|
+
subset = df[["col1", "col2"]] # view (메모리 공유)
|
|
190
|
+
subset = df[["col1", "col2"]].copy() # copy (별도 메모리)
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
---
|
|
194
|
+
|
|
195
|
+
## 7. 연산 속도 비교표
|
|
196
|
+
|
|
197
|
+
| Operation | Slow Method | Fast Method | Speedup |
|
|
198
|
+
|-----------|-------------|-------------|---------|
|
|
199
|
+
| 조건부 할당 | apply(lambda) | np.where | 10-100x |
|
|
200
|
+
| 문자열 연산 | apply(str) | .str accessor | 5-20x |
|
|
201
|
+
| 반복 계산 | for loop | vectorized | 100-1000x |
|
|
202
|
+
| 다중 집계 | 여러 groupby | 단일 .agg() | 2-5x |
|
|
203
|
+
| 필터링 | boolean indexing | .query() | 1.5-3x |
|
|
204
|
+
|
|
205
|
+
---
|
|
206
|
+
|
|
207
|
+
## 8. 성능 측정
|
|
208
|
+
|
|
209
|
+
```python
|
|
210
|
+
import time
|
|
211
|
+
|
|
212
|
+
# 실행 시간 측정
|
|
213
|
+
start = time.time()
|
|
214
|
+
result = df.groupby("category")["value"].sum()
|
|
215
|
+
print(f"Elapsed: {time.time() - start:.2f}s")
|
|
216
|
+
|
|
217
|
+
# 메모리 프로파일링
|
|
218
|
+
import memory_profiler
|
|
219
|
+
%memit df.groupby("category")["value"].sum()
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
---
|
|
223
|
+
|
|
224
|
+
## Quick Reference
|
|
225
|
+
|
|
226
|
+
```python
|
|
227
|
+
# 대용량 분석 체크리스트
|
|
228
|
+
# 1. dtype 최적화 (data_loading 스킬 참조)
|
|
229
|
+
# 2. 필요한 컬럼만 선택
|
|
230
|
+
# 3. 벡터화 연산 사용 (apply 대신 np.where/np.select)
|
|
231
|
+
# 4. eval()/query() 활용
|
|
232
|
+
# 5. groupby에 sort=False 추가
|
|
233
|
+
# 6. 중간 결과 삭제 (del + gc.collect())
|
|
234
|
+
# 7. 메모리 부족 시 Dask/Polars 전환
|
|
235
|
+
```
|
|
236
|
+
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: data_cleaning_pipeline
|
|
3
|
+
description: 'Data Cleaning Pipeline Template. 이런 요청에 쓴다: 데이터 정제, data cleaning, 전처리, preprocessing, 결측값'
|
|
4
|
+
---
|
|
5
|
+
## Data Cleaning Pipeline Template
|
|
6
|
+
1. **Duplicate Removal**: `df.drop_duplicates()`
|
|
7
|
+
2. **Missing Values**: Strategy per column (drop/impute mean/median/mode/KNN)
|
|
8
|
+
3. **Type Conversion**: Ensure correct dtypes (numeric, datetime, categorical)
|
|
9
|
+
4. **Outlier Treatment**: Cap/floor, remove, or transform (log, sqrt)
|
|
10
|
+
5. **Encoding**: Label encoding for ordinal, One-hot for nominal
|
|
11
|
+
6. **Scaling**: StandardScaler or MinMaxScaler for numerical features
|
|
12
|
+
7. **Validation**: `df.info()`, `df.isnull().sum()`, shape check
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: data-loading
|
|
3
|
+
description: 대용량 파일 로드 최적화. CSV/Parquet 파일이 100MB 이상이거나 메모리 부족 시 사용. chunking, sampling, dtype 최적화, Dask/Polars 전환 가이드 제공.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Data Loading Optimization Guide
|
|
7
|
+
|
|
8
|
+
대용량 데이터셋 로드 시 메모리 효율적인 방법을 안내합니다.
|
|
9
|
+
|
|
10
|
+
## Resource Tiers
|
|
11
|
+
|
|
12
|
+
### TIER_SMALL: 파일 < 100MB, RAM 여유 충분
|
|
13
|
+
직접 로드 OK. 특별한 최적화 불필요.
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
import pandas as pd
|
|
17
|
+
df = pd.read_csv("data.csv")
|
|
18
|
+
# 또는
|
|
19
|
+
df = pd.read_parquet("data.parquet")
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
### TIER_MEDIUM: 파일 100MB ~ 1GB
|
|
23
|
+
dtype 최적화 + 필요한 컬럼만 로드
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
import pandas as pd
|
|
27
|
+
|
|
28
|
+
# 1. 필요한 컬럼만 로드 (메모리 최대 90% 절약)
|
|
29
|
+
df = pd.read_csv("data.csv", usecols=["col1", "col2", "col3"])
|
|
30
|
+
|
|
31
|
+
# 2. dtype 최적화 지정
|
|
32
|
+
dtype_map = {
|
|
33
|
+
"id": "int32", # int64 → int32 (50% 절약)
|
|
34
|
+
"category_col": "category", # string → category (90%+ 절약)
|
|
35
|
+
"float_col": "float32", # float64 → float32 (50% 절약)
|
|
36
|
+
}
|
|
37
|
+
df = pd.read_csv("data.csv", dtype=dtype_map)
|
|
38
|
+
|
|
39
|
+
# 3. Parquet 사용 시 (자동 압축, 컬럼 선택 지원)
|
|
40
|
+
df = pd.read_parquet("data.parquet", columns=["col1", "col2"])
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### TIER_LARGE: 파일 > 1GB 또는 메모리 부족
|
|
44
|
+
Chunking 또는 Dask/Polars 사용
|
|
45
|
+
|
|
46
|
+
#### Option A: Chunking (단순 집계용)
|
|
47
|
+
```python
|
|
48
|
+
import pandas as pd
|
|
49
|
+
|
|
50
|
+
# 청크 단위 처리 (메모리: 청크 크기만 사용)
|
|
51
|
+
chunks = pd.read_csv("large_data.csv", chunksize=100_000)
|
|
52
|
+
|
|
53
|
+
# 예: 청크별 집계 후 합산
|
|
54
|
+
total_count = 0
|
|
55
|
+
for chunk in chunks:
|
|
56
|
+
total_count += len(chunk[chunk["status"] == "active"])
|
|
57
|
+
|
|
58
|
+
print(f"Active records: {total_count}")
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
#### Option B: Dask (복잡한 연산, groupby 등)
|
|
62
|
+
```python
|
|
63
|
+
import dask.dataframe as dd
|
|
64
|
+
|
|
65
|
+
# Dask로 로드 (lazy evaluation, 메모리 효율적)
|
|
66
|
+
ddf = dd.read_csv("large_data.csv")
|
|
67
|
+
|
|
68
|
+
# pandas처럼 사용 (내부적으로 청크 처리)
|
|
69
|
+
result = ddf.groupby("category")["value"].mean().compute()
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
#### Option C: Polars (고성능 대안)
|
|
73
|
+
```python
|
|
74
|
+
import polars as pl
|
|
75
|
+
|
|
76
|
+
# Polars: Rust 기반, pandas보다 30x 빠름
|
|
77
|
+
df = pl.read_csv("large_data.csv")
|
|
78
|
+
|
|
79
|
+
# 또는 lazy mode (메모리 최적화)
|
|
80
|
+
df = pl.scan_csv("large_data.csv").filter(
|
|
81
|
+
pl.col("date") > "2024-01-01"
|
|
82
|
+
).collect()
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## dtype 최적화 상세
|
|
86
|
+
|
|
87
|
+
| Original Type | Optimized Type | Memory Savings | When to Use |
|
|
88
|
+
|---------------|----------------|----------------|-------------|
|
|
89
|
+
| int64 | int32 | 50% | 값 범위가 ±2B 이내 |
|
|
90
|
+
| int64 | int16 | 75% | 값 범위가 ±32K 이내 |
|
|
91
|
+
| int64 | int8 | 87.5% | 값 범위가 ±127 이내 |
|
|
92
|
+
| float64 | float32 | 50% | 소수점 7자리 정밀도 OK |
|
|
93
|
+
| object (string) | category | 90%+ | 고유값 < 50% |
|
|
94
|
+
|
|
95
|
+
### 자동 dtype 최적화 함수
|
|
96
|
+
```python
|
|
97
|
+
def optimize_dtypes(df):
|
|
98
|
+
"""DataFrame의 dtype을 자동 최적화"""
|
|
99
|
+
for col in df.columns:
|
|
100
|
+
col_type = df[col].dtype
|
|
101
|
+
|
|
102
|
+
if col_type == "int64":
|
|
103
|
+
if df[col].min() >= 0:
|
|
104
|
+
if df[col].max() < 255:
|
|
105
|
+
df[col] = df[col].astype("uint8")
|
|
106
|
+
elif df[col].max() < 65535:
|
|
107
|
+
df[col] = df[col].astype("uint16")
|
|
108
|
+
else:
|
|
109
|
+
df[col] = df[col].astype("uint32")
|
|
110
|
+
else:
|
|
111
|
+
if df[col].min() > -128 and df[col].max() < 127:
|
|
112
|
+
df[col] = df[col].astype("int8")
|
|
113
|
+
elif df[col].min() > -32768 and df[col].max() < 32767:
|
|
114
|
+
df[col] = df[col].astype("int16")
|
|
115
|
+
else:
|
|
116
|
+
df[col] = df[col].astype("int32")
|
|
117
|
+
|
|
118
|
+
elif col_type == "float64":
|
|
119
|
+
df[col] = df[col].astype("float32")
|
|
120
|
+
|
|
121
|
+
elif col_type == "object":
|
|
122
|
+
num_unique = df[col].nunique()
|
|
123
|
+
num_total = len(df[col])
|
|
124
|
+
if num_unique / num_total < 0.5: # 50% 미만 고유값
|
|
125
|
+
df[col] = df[col].astype("category")
|
|
126
|
+
|
|
127
|
+
return df
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## 파일 포맷별 권장사항
|
|
131
|
+
|
|
132
|
+
| Format | Read Speed | Write Speed | Compression | Best For |
|
|
133
|
+
|--------|------------|-------------|-------------|----------|
|
|
134
|
+
| CSV | Slow | Slow | None | 호환성, 간단한 데이터 |
|
|
135
|
+
| Parquet | Fast | Fast | Excellent | 대용량 분석, 컬럼 선택 |
|
|
136
|
+
| Feather | Fastest | Fastest | Good | pandas 간 데이터 교환 |
|
|
137
|
+
| HDF5 | Fast | Fast | Good | 다차원 배열 |
|
|
138
|
+
|
|
139
|
+
### CSV → Parquet 변환 (일회성 비용으로 이후 로드 빠름)
|
|
140
|
+
```python
|
|
141
|
+
# 최초 1회 변환
|
|
142
|
+
df = pd.read_csv("data.csv")
|
|
143
|
+
df.to_parquet("data.parquet", compression="snappy")
|
|
144
|
+
|
|
145
|
+
# 이후 빠른 로드
|
|
146
|
+
df = pd.read_parquet("data.parquet")
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
## 메모리 확인 방법
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
# DataFrame 메모리 사용량 확인
|
|
153
|
+
print(df.memory_usage(deep=True).sum() / 1024**2, "MB")
|
|
154
|
+
|
|
155
|
+
# 컬럼별 메모리 사용량
|
|
156
|
+
print(df.memory_usage(deep=True) / 1024**2)
|
|
157
|
+
```
|
|
158
|
+
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: data_quality_report
|
|
3
|
+
description: 'Data Quality Report Template. 이런 요청에 쓴다: data quality, profiling, completeness, 데이터 품질, 프로파일링, 데이터 검증'
|
|
4
|
+
---
|
|
5
|
+
## Data Quality Report Template
|
|
6
|
+
1. **Shape & Types**: `df.shape`, `df.dtypes`, `df.info()`
|
|
7
|
+
2. **Missing Values**: Per-column null counts and percentages, missingness patterns
|
|
8
|
+
3. **Duplicates**: `df.duplicated().sum()`, identify duplicate columns
|
|
9
|
+
4. **Cardinality**: Unique counts per column, detect near-constant features
|
|
10
|
+
5. **Value Ranges**: Min/max/mean/std for numerics, frequency tables for categoricals
|
|
11
|
+
6. **Consistency Checks**: Data type mismatches, negative values in positive-only fields
|
|
12
|
+
7. **Automated Profiling**: `ydata_profiling.ProfileReport(df)` for full HTML report
|
|
13
|
+
8. **Summary**: Data readiness score, list of issues requiring action
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: dimensionality_reduction
|
|
3
|
+
description: 'Dimensionality Reduction Template. 이런 요청에 쓴다: dimensionality reduction, pca, t-sne, umap, 차원축소'
|
|
4
|
+
---
|
|
5
|
+
## Dimensionality Reduction Template
|
|
6
|
+
1. **Scaling**: `StandardScaler()` — required before PCA/t-SNE/UMAP
|
|
7
|
+
2. **PCA**: `PCA(n_components=0.95)` — retain 95% variance, inspect explained variance ratio
|
|
8
|
+
3. **Scree Plot**: Bar chart of explained variance per component
|
|
9
|
+
4. **t-SNE**: `TSNE(perplexity=30)` for 2D visualization of high-dim data
|
|
10
|
+
5. **UMAP**: `umap.UMAP(n_neighbors=15)` for faster, more scalable alternative
|
|
11
|
+
6. **Visualization**: 2D scatter plot colored by target or cluster labels
|
|
12
|
+
7. **Feature Loadings**: For PCA, inspect `pca.components_` to understand component meaning
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: emr_script_development
|
|
3
|
+
description: 'EMR Script Development Workflow. 이런 요청에 쓴다: emr, pyspark, spark-submit, emr step, spark job, spark 스크립트'
|
|
4
|
+
---
|
|
5
|
+
## EMR Script Development Workflow
|
|
6
|
+
1. **Script**: PySpark with argparse, SparkSession, S3 I/O
|
|
7
|
+
2. **Local Test**: spark-submit --master local[*]
|
|
8
|
+
3. **Unit Test**: pytest with small local data
|
|
9
|
+
|
|
10
|
+
## Guidelines
|
|
11
|
+
- argparse 기반 CLI 인터페이스 (--input, --output, --date 등)
|
|
12
|
+
- SparkSession.builder로 세션 생성, finally에서 spark.stop()
|
|
13
|
+
- S3 경로는 파라미터화 (하드코딩 금지)
|
|
14
|
+
- 내장 함수 우선 사용 (UDF 최소화)
|
|
15
|
+
- AQE(Adaptive Query Execution) 기본 활성화
|
|
16
|
+
- 유닛테스트: pytest + local[*] SparkSession
|
|
17
|
+
- EMR Step JSON 포함 시 command-runner.jar 패턴 사용
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: experiment_tracking
|
|
3
|
+
description: 'Experiment Tracking Template. 이런 요청에 쓴다: mlflow, wandb, experiment tracking, run logging, 실험 추적, 모델 관리'
|
|
4
|
+
---
|
|
5
|
+
## Experiment Tracking Template
|
|
6
|
+
1. **Setup**: `mlflow.set_tracking_uri()` / `wandb.init(project='name')`
|
|
7
|
+
2. **Log Parameters**: `mlflow.log_params(params)` / `wandb.config.update(params)`
|
|
8
|
+
3. **Log Metrics**: `mlflow.log_metric('f1', score)` / `wandb.log({'f1': score})`
|
|
9
|
+
4. **Log Artifacts**: Save model, plots, data samples as artifacts
|
|
10
|
+
5. **Model Registry**: `mlflow.sklearn.log_model()` for versioned model storage
|
|
11
|
+
6. **Compare Runs**: Use UI dashboard to compare experiments side-by-side
|
|
12
|
+
7. **Best Run Selection**: Query best run by metric, load for deployment
|
|
13
|
+
8. **Reproducibility**: Log git hash, environment, random seeds
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: feature_importance_analysis
|
|
3
|
+
description: 'Feature Importance Template. 이런 요청에 쓴다: feature importance, 특성 중요도, 변수 중요도, 어떤 변수'
|
|
4
|
+
---
|
|
5
|
+
## Feature Importance Template
|
|
6
|
+
1. **Permutation Importance**: `sklearn.inspection.permutation_importance()`
|
|
7
|
+
2. **Tree-based**: `model.feature_importances_` for RF/GBM
|
|
8
|
+
3. **SHAP Values**: `shap.TreeExplainer()` → `shap.summary_plot()`
|
|
9
|
+
4. **Correlation-based**: Feature-target correlation ranking
|
|
10
|
+
5. **Visualization**: Bar plot of top-N features sorted by importance
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: hyperparameter_tuning
|
|
3
|
+
description: 'Hyperparameter Tuning Template. 이런 요청에 쓴다: hyperparameter, optuna, gridsearch, grid search, 하이퍼파라미터, 튜닝'
|
|
4
|
+
---
|
|
5
|
+
## Hyperparameter Tuning Template
|
|
6
|
+
1. **Define Search Space**: List hyperparameters and their ranges
|
|
7
|
+
2. **GridSearchCV**: `GridSearchCV(estimator, param_grid, cv=5, scoring='f1')`
|
|
8
|
+
3. **RandomizedSearchCV**: For large search spaces, `RandomizedSearchCV(n_iter=100)`
|
|
9
|
+
4. **Optuna**: `optuna.create_study()` → `study.optimize(objective, n_trials=100)`
|
|
10
|
+
5. **Best Params**: `search.best_params_`, `study.best_trial.params`
|
|
11
|
+
6. **Retrain**: Fit final model with best params on full training set
|
|
12
|
+
7. **Validate**: Evaluate on hold-out test set, compare with baseline
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: hypothesis_testing
|
|
3
|
+
description: 'Hypothesis Testing Template. 이런 요청에 쓴다: hypothesis, t-test, anova, p-value, a/b test, 가설검정'
|
|
4
|
+
---
|
|
5
|
+
## Hypothesis Testing Template
|
|
6
|
+
1. **Formulate Hypotheses**: H₀ (null) and H₁ (alternative), significance level α
|
|
7
|
+
2. **Check Assumptions**: Normality (Shapiro-Wilk), equal variance (Levene's test)
|
|
8
|
+
3. **Select Test**: t-test (2 groups), ANOVA (3+ groups), chi-squared (categorical), Mann-Whitney (non-parametric)
|
|
9
|
+
4. **Execute**: `scipy.stats.ttest_ind()`, `f_oneway()`, `chi2_contingency()`
|
|
10
|
+
5. **Interpret**: p-value vs α, effect size (Cohen's d), confidence interval
|
|
11
|
+
6. **Visualize**: Box plots, violin plots, or bar charts with error bars
|
|
12
|
+
7. **Report**: State conclusion in context, mention limitations
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: imbalanced_data_handling
|
|
3
|
+
description: 'Imbalanced Data Handling Template. 이런 요청에 쓴다: imbalanced, smote, oversampling, undersampling, class weight, 불균형'
|
|
4
|
+
---
|
|
5
|
+
## Imbalanced Data Handling Template
|
|
6
|
+
1. **Diagnose**: `df[target].value_counts(normalize=True)` — check class ratios
|
|
7
|
+
2. **Baseline**: Train model without balancing, measure recall for minority class
|
|
8
|
+
3. **Resampling**: SMOTE (`imblearn.over_sampling.SMOTE`), RandomUnderSampler, or SMOTEENN
|
|
9
|
+
4. **Class Weights**: `model = RandomForestClassifier(class_weight='balanced')`
|
|
10
|
+
5. **Threshold Tuning**: Adjust decision threshold using precision-recall curve
|
|
11
|
+
6. **Metrics**: Use F1, balanced accuracy, PR-AUC instead of accuracy
|
|
12
|
+
7. **Evaluation**: Stratified K-Fold CV to preserve class distribution
|