> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# pandas 마이그레이션

> pandas에서 DataStore로 마이그레이션하는 단계별 가이드

이 가이드는 호환성을 유지하면서 성능을 개선할 수 있도록 기존 pandas 코드를 DataStore로 마이그레이션하는 방법을 안내합니다.

## 한 줄로 마이그레이션

가장 간단한 마이그레이션 방법은 import문을 변경하는 것입니다:

```python theme={null}
# Before (pandas)
import pandas as pd

# After (DataStore)
from chdb import datastore as pd
```

이제 끝입니다! 대부분의 pandas 코드는 수정 없이 그대로 작동합니다.

## 단계별 마이그레이션

**1. chDB 설치**

```bash theme={null}
pip install "chdb>=4.0"
```

**2. import 구문 변경**

```python theme={null}
# 다음을:
import pandas as pd

# 이렇게 변경합니다:
from chdb import datastore as pd
```

**3. 코드 테스트**

기존 코드를 실행해 보세요. 대부분의 연산은 변경 없이 그대로 작동합니다:

```python theme={null}
from chdb import datastore as pd

# 모두 동일하게 작동합니다
df = pd.read_csv("data.csv")
result = df[df['age'] > 25]
grouped = df.groupby('city')['salary'].mean()
df.to_csv("output.csv")
```

**4. 차이점 확인 및 처리**

일부 연산은 다르게 동작합니다. 아래의 [Key Differences](#differences)를 참조하세요.

***

## 그대로 작동하는 항목

### 데이터 로딩

```python theme={null}
# All these work the same
df = pd.read_csv("data.csv")
df = pd.read_parquet("data.parquet")
df = pd.read_json("data.json")
df = pd.read_excel("data.xlsx")
```

### 필터링

```python theme={null}
# Boolean indexing
df[df['age'] > 25]
df[(df['age'] > 25) & (df['city'] == 'NYC')]

# query() method
df.query('age > 25 and salary > 50000')
```

### 선택 영역

```python theme={null}
# Column selection
df['name']
df[['name', 'age']]

# Row selection
df.head(10)
df.tail(10)
df.iloc[0:100]
```

### GroupBy와 집계

```python theme={null}
# GroupBy
df.groupby('city')['salary'].mean()
df.groupby(['city', 'dept']).agg({'salary': ['sum', 'mean']})
```

### 정렬

```python theme={null}
df.sort_values('salary', ascending=False)
df.sort_values(['city', 'age'])
```

### 문자열 연산

```python theme={null}
df['name'].str.upper()
df['name'].str.contains('John')
df['name'].str.len()
```

### DateTime 연산

```python theme={null}
df['date'].dt.year
df['date'].dt.month
df['date'].dt.dayofweek
```

### I/O 작업

```python theme={null}
df.to_csv("output.csv")
df.to_parquet("output.parquet")
df.to_json("output.json")
```

***

## 주요 차이점

### 1. 지연 실행

DataStore 작업은 지연 실행되며, 결과가 필요할 때까지 실제로 실행되지 않습니다.

**pandas:**

```python theme={null}
# Executes immediately
result = df[df['age'] > 25]
print(type(result))  # pandas.DataFrame
```

**DataStore:**

```python theme={null}
# Builds query, doesn't execute yet
result = ds[ds['age'] > 25]
print(type(result))  # DataStore (lazy)

# Executes when you need the data
print(result)        # Triggers execution
df = result.to_df()  # Triggers execution
```

### 2. 반환 유형

| Operation | pandas 반환값 | DataStore 반환값 |
| - | - | - |
| `df['col']` | Series | ColumnExpr (지연 실행) |
| `df[['a', 'b']]` | DataFrame | DataStore (지연 실행) |
| `df[condition]` | DataFrame | DataStore (지연 실행) |
| `df.groupby('x')` | GroupBy | LazyGroupBy |

### 3. inplace 매개변수 미지원

DataStore는 `inplace=True`를 지원하지 않습니다. 항상 반환값을 사용하세요.

**pandas:**

```python theme={null}
df.drop(columns=['col'], inplace=True)
```

**DataStore:**

```python theme={null}
ds = ds.drop(columns=['col'])  # Assign the result
```

### 4. DataStore 비교하기

pandas는 DataStore 객체를 인식하지 않으므로, 비교할 때는 `to_pandas()`를 사용하세요:

```python theme={null}
# This may not work as expected
df == ds  # pandas doesn't know DataStore

# Do this instead
df.equals(ds.to_pandas())
```

### 5. 행 순서

DataStore는 파일 소스(예: SQL 데이터베이스)의 행 순서를 유지하지 않을 수 있습니다. 명시적으로 정렬하세요:

```python theme={null}
# pandas preserves order
df = pd.read_csv("data.csv")

# DataStore - use sort for guaranteed order
ds = pd.read_csv("data.csv")
ds = ds.sort('id')  # Explicit ordering
```

***

## 마이그레이션 패턴

### 패턴 1: 읽기-분석-쓰기

```python theme={null}
# pandas
import pandas as pd
df = pd.read_csv("data.csv")
result = df[df['amount'] > 100].groupby('category')['amount'].sum()
result.to_csv("output.csv")

# DataStore - same code works!
from chdb import datastore as pd
df = pd.read_csv("data.csv")
result = df[df['amount'] > 100].groupby('category')['amount'].sum()
result.to_csv("output.csv")
```

### 패턴 2: pandas 연산용 DataFrame

pandas 전용 기능이 필요하다면 마지막에 변환하세요:

```python theme={null}
from chdb import datastore as pd

# Fast DataStore operations
ds = pd.read_csv("large_data.csv")
ds = ds.filter(ds['date'] >= '2024-01-01')
ds = ds.filter(ds['amount'] > 100)

# Convert to pandas for specific features
df = ds.to_df()
df_pivoted = df.pivot_table(...)  # pandas-specific
```

### 패턴 3: 혼합 워크플로우

```python theme={null}
from chdb import datastore as pd
import pandas

# Start with DataStore for fast filtering
ds = pd.read_csv("huge_file.csv")  # 10M rows
ds = ds.filter(ds['year'] == 2024)  # Fast SQL filter
ds = ds.select('col1', 'col2', 'col3')  # Column pruning

# Convert for pandas-specific operations
df = ds.to_df()  # Now only ~100K rows
result = df.apply(complex_custom_function)  # pandas
```

***

## 성능 비교

대규모 데이터셋에서는 DataStore가 훨씬 빠릅니다:

| 작업 | pandas | DataStore | 속도 향상 |
| - | - | - | - |
| GroupBy count | 347ms | 17ms | **19.93x** |
| 복합 파이프라인 | 2,047ms | 380ms | **5.39x** |
| Filter+Sort+Head | 1,537ms | 350ms | **4.40x** |
| GroupBy agg | 406ms | 141ms | **2.88x** |

*1,000만 행 벤치마크*

***

## 마이그레이션 문제 해결

### 문제: 연산이 작동하지 않음

일부 pandas 연산은 지원되지 않을 수 있습니다. 다음 사항을 확인하세요.

1. 해당 연산이 [호환성 목록](https://clickhouse.com/docs/ko/chdb/datastore/pandas-compat.md)에 있습니까?
2. 먼저 pandas로 변환해 보세요: `ds.to_df().operation()`

### 문제: 결과가 다름

무슨 일이 일어나는지 파악하려면 디버그 로깅을 활성화하세요:

```python theme={null}
from chdb.datastore.config import config
config.enable_debug()

# View the SQL being generated
ds.filter(ds['x'] > 10).explain()
```

### 문제: 성능 저하

실행 패턴을 확인하십시오:

```python theme={null}
# Bad: Multiple small executions
for i in range(1000):
    result = ds.filter(ds['id'] == i).to_df()

# Good: Single execution
result = ds.filter(ds['id'].isin(ids)).to_df()
```

### 문제: 타입 불일치

DataStore의 타입 추론 결과가 다를 수 있습니다:

```python theme={null}
# Check types
print(ds.dtypes)

# Force conversion
ds['col'] = ds['col'].astype('int64')
```

***

## 점진적 마이그레이션 전략

### 1주차: 호환성 테스트

```python theme={null}
# Keep both imports
import pandas as pd
from chdb import datastore as ds

# Compare results
pdf = pd.read_csv("data.csv")
dsf = ds.read_csv("data.csv")

# Verify they match
assert pdf.equals(dsf.to_pandas())
```

### 2주차: 간단한 스크립트 전환

다음과 같은 스크립트부터 시작하세요:

* 대용량 파일을 읽음
* 필터링과 집계를 수행함
* 사용자 정의 적용 함수를 사용하지 않음

### 3주차: 복잡한 경우 처리

사용자 지정 함수가 포함된 스크립트의 경우:

```python theme={null}
from chdb import datastore as pd

# Let DataStore handle the heavy lifting
ds = pd.read_csv("data.csv")
ds = ds.filter(ds['year'] == 2024)  # SQL

# Convert for custom work
df = ds.to_df()
result = df.apply(my_custom_function)
```

### 4주 차: 전체 마이그레이션

모든 스크립트를 DataStore import로 전환하세요.

***

## FAQ

### pandas와 DataStore를 모두 사용할 수 있나요?

네! 둘 사이를 자유롭게 변환할 수 있습니다:

```python theme={null}
from chdb import datastore as ds
import pandas as pd

# DataStore to pandas
df = ds_result.to_pandas()

# pandas to DataStore  
ds = ds.DataFrame(pd_result)
```

### 기존 테스트도 계속 통과하나요?

대부분의 테스트는 통과합니다. 비교 테스트는 `pandas`로 변환하십시오:

```python theme={null}
def test_my_function():
    result = my_function()
    expected = pd.DataFrame(...)
    pd.testing.assert_frame_equal(result.to_pandas(), expected)
```

### Jupyter에서 DataStore를 사용할 수 있나요?

네! DataStore는 Jupyter notebooks에서 사용할 수 있습니다:

```python theme={null}
from chdb import datastore as pd

ds = pd.read_csv("data.csv")
ds.head()  # Displays nicely in Jupyter
```

### 이슈는 어떻게 보고하나요?

호환성 이슈를 발견하면 다음 페이지에 보고하십시오:
[https://github.com/chdb-io/chdb/issues](https://github.com/chdb-io/chdb/issues)
