> ## 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 に移行してパフォーマンスを向上させる方法を説明します。

<div id="one-line">
  ## ワンライナーでの移行
</div>

最も簡単なのは、インポート文を変更するだけです:

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

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

以上です！ほとんどの pandas コードはそのまま動作します。

<div id="step-by-step">
  ## 段階的な移行
</div>

<Steps>
  <Step title="chDB をインストール" id="step-1">
    ```bash theme={null}
    pip install "chdb>=4.0"
    ```
  </Step>

  <Step title="インポートを変更" id="step-2">
    ```python theme={null}
    # これを:
    import pandas as pd

    # これに変更:
    from chdb import datastore as pd
    ```
  </Step>

  <Step title="コードをテスト" id="step-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")
    ```
  </Step>

  <Step title="相違点に対応" id="step-4">
    一部の操作は挙動が異なります。以下の[主な違い](#differences)を参照してください。
  </Step>
</Steps>

***

<div id="works-unchanged">
  ## そのまま動作するもの
</div>

<div id="loading-unchanged">
  ### データの読み込み
</div>

```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")
```

<div id="filtering-unchanged">
  ### フィルタリング
</div>

```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')
```

<div id="selection-unchanged">
  ### 選択範囲
</div>

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

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

<div id="groupby-unchanged">
  ### GroupBy と集計
</div>

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

<div id="sorting-unchanged">
  ### ソート
</div>

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

<div id="string-unchanged">
  ### 文字列操作
</div>

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

<div id="datetime-unchanged">
  ### DateTime の操作
</div>

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

<div id="io-unchanged">
  ### I/O 操作
</div>

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

***

<div id="differences">
  ## 主な違い
</div>

<div id="lazy">
  ### 1. 遅延評価
</div>

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
```

<div id="return-types">
  ### 2. 戻り値の型
</div>

| 操作                | pandas の戻り値 | DataStore の戻り値    |
| ----------------- | ----------- | ----------------- |
| `df['col']`       | Series      | ColumnExpr (遅延実行) |
| `df[['a', 'b']]`  | DataFrame   | DataStore (遅延実行)  |
| `df[condition]`   | DataFrame   | DataStore (遅延実行)  |
| `df.groupby('x')` | GroupBy     | LazyGroupBy       |

<div id="no-inplace">
  ### 3. inplace パラメータはありません
</div>

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
```

<div id="comparing">
  ### 4. DataStore の比較
</div>

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())
```

<div id="row-order">
  ### 5. 行の順序
</div>

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
```

***

<div id="patterns">
  ## 移行パターン
</div>

<div id="pattern-1">
  ### パターン 1: 読み込み・分析・書き込み
</div>

```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")
```

<div id="pattern-2">
  ### パターン2: pandasで操作するDataFrame
</div>

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
```

<div id="pattern-3">
  ### パターン3: 混在ワークフロー
</div>

```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
```

***

<div id="performance">
  ## 性能比較
</div>

大規模なデータセットでは、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万行でのベンチマーク*

***

<div id="troubleshooting">
  ## 移行のトラブルシューティング
</div>

<div id="issue-op">
  ### 問題: 操作が機能しない
</div>

一部の pandas の操作はサポートされていないことがあります。次の点を確認してください。

1. その操作は[互換性リスト](/docs/ja/chdb/datastore/pandas-compat)に含まれていますか？
2. まず pandas に変換してから試してください: `ds.to_df().operation()`

<div id="issue-results">
  ### 問題: 結果が異なる
</div>

何が起きているかを把握するため、デバッグログを有効にします：

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

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

<div id="issue-slow">
  ### 問題: パフォーマンスが低い
</div>

実行パターンを確認してください。

```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()
```

<div id="issue-types">
  ### 問題: 型の不一致
</div>

DataStore では、型の推論結果が異なる場合があります:

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

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

***

<div id="gradual">
  ## 段階的移行戦略
</div>

<div id="week-1">
  ### 第1週: 互換性をテスト
</div>

```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())
```

<div id="week-2">
  ### 第2週: 単純なスクリプトを移行する
</div>

まずは、次のようなスクリプトから始めます。

* 大きなファイルを読み込む
* フィルタリングと集約を行う
* カスタムの apply 関数を使用しない

<div id="week-3">
  ### 第3週: 複雑なケースに対応
</div>

カスタム関数を含むスクリプトの場合:

```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)
```

<div id="week-4">
  ### 第4週: 完全移行
</div>

すべてのスクリプトのインポートをDataStoreに切り替えます。

***

<div id="faq">
  ## よくある質問
</div>

<div id="faq-both">
  ### pandas と DataStore の両方を使用できますか？
</div>

はい。両者は自由に相互変換できます。

```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)
```

<div id="faq-tests">
  ### テストはこれまでどおり通りますか？
</div>

ほとんどのテストは通るはずです。比較用のテストでは、pandas に変換してください：

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

<div id="faq-jupyter">
  ### Jupyter で DataStore を使用できますか？
</div>

はい！DataStore は Jupyter ノートブックで利用できます。

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

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

<div id="faq-issues">
  ### issue はどのように報告すればよいですか？
</div>

互換性に関する issue を見つけた場合は、以下で報告してください。
[https://github.com/chdb-io/chdb/issues](https://github.com/chdb-io/chdb/issues)
