> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-postgresql-tls-support.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Migration from pandas

> Step-by-step guide to migrate from pandas to DataStore

This guide helps you migrate existing pandas code to DataStore for better performance while maintaining compatibility.

<h2 id="one-line">
  The One-Line Migration
</h2>

The simplest migration is changing your import:

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

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

That's it! Most pandas code works unchanged.

<h2 id="step-by-step">
  Step-by-Step Migration
</h2>

<Steps>
  <Step title="Install chDB" id="step-1">
    ```bash theme={null}
    pip install "chdb>=4.0"
    ```
  </Step>

  <Step title="Change the Import" id="step-2">
    ```python theme={null}
    # Change this:
    import pandas as pd

    # To this:
    from chdb import datastore as pd
    ```
  </Step>

  <Step title="Test Your Code" id="step-3">
    Run your existing code. Most operations work unchanged:

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

    # These all work the same
    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="Handle Any Differences" id="step-4">
    A few operations behave differently. See [Key Differences](#differences) below.
  </Step>
</Steps>

***

<h2 id="works-unchanged">
  What Works Unchanged
</h2>

<h3 id="loading-unchanged">
  Data Loading
</h3>

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

<h3 id="filtering-unchanged">
  Filtering
</h3>

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

<h3 id="selection-unchanged">
  Selection
</h3>

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

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

<h3 id="groupby-unchanged">
  GroupBy and Aggregation
</h3>

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

<h3 id="sorting-unchanged">
  Sorting
</h3>

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

<h3 id="string-unchanged">
  String Operations
</h3>

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

<h3 id="datetime-unchanged">
  DateTime Operations
</h3>

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

<h3 id="io-unchanged">
  I/O Operations
</h3>

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

***

<h2 id="differences">
  Key Differences
</h2>

<h3 id="lazy">
  1. Lazy Evaluation
</h3>

DataStore operations are lazy - they don't execute until results are needed.

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

<h3 id="return-types">
  2. Return Types
</h3>

| Operation         | pandas Returns | DataStore Returns |
| ----------------- | -------------- | ----------------- |
| `df['col']`       | Series         | ColumnExpr (lazy) |
| `df[['a', 'b']]`  | DataFrame      | DataStore (lazy)  |
| `df[condition]`   | DataFrame      | DataStore (lazy)  |
| `df.groupby('x')` | GroupBy        | LazyGroupBy       |

<h3 id="no-inplace">
  3. No inplace Parameter
</h3>

DataStore doesn't support `inplace=True`. Always use the return value:

**pandas:**

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

**DataStore:**

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

<h3 id="comparing">
  4. Comparing DataStores
</h3>

pandas doesn't recognize DataStore objects, so use `to_pandas()` for comparison:

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

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

<h3 id="row-order">
  5. Row Order
</h3>

DataStore may not preserve row order for file sources (like SQL databases). Use explicit sorting:

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

***

<h2 id="patterns">
  Migration Patterns
</h2>

<h3 id="pattern-1">
  Pattern 1: Read-Analyze-Write
</h3>

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

<h3 id="pattern-2">
  Pattern 2: DataFrame with pandas Operations
</h3>

If you need pandas-specific features, convert at the end:

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

<h3 id="pattern-3">
  Pattern 3: Mixed Workflow
</h3>

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

***

<h2 id="performance">
  Performance Comparison
</h2>

DataStore is significantly faster for large datasets:

| Operation        | pandas  | DataStore | Speedup    |
| ---------------- | ------- | --------- | ---------- |
| GroupBy count    | 347ms   | 17ms      | **19.93x** |
| Complex pipeline | 2,047ms | 380ms     | **5.39x**  |
| Filter+Sort+Head | 1,537ms | 350ms     | **4.40x**  |
| GroupBy agg      | 406ms   | 141ms     | **2.88x**  |

*Benchmark on 10M rows*

***

<h2 id="troubleshooting">
  Troubleshooting Migration
</h2>

<h3 id="issue-op">
  Issue: Operation Not Working
</h3>

Some pandas operations may not be supported. Check:

1. Is the operation in the [compatibility list](/chdb/datastore/pandas-compat)?
2. Try converting to pandas first: `ds.to_df().operation()`

<h3 id="issue-results">
  Issue: Different Results
</h3>

Enable debug logging to understand what's happening:

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

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

<h3 id="issue-slow">
  Issue: Slow Performance
</h3>

Check your execution pattern:

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

<h3 id="issue-types">
  Issue: Type Mismatches
</h3>

DataStore may infer types differently:

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

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

***

<h2 id="gradual">
  Gradual Migration Strategy
</h2>

<h3 id="week-1">
  Week 1: Test Compatibility
</h3>

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

<h3 id="week-2">
  Week 2: Switch Simple Scripts
</h3>

Start with scripts that:

* Read large files
* Do filtering and aggregation
* Don't use custom apply functions

<h3 id="week-3">
  Week 3: Handle Complex Cases
</h3>

For scripts with custom functions:

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

<h3 id="week-4">
  Week 4: Full Migration
</h3>

Switch all scripts to DataStore import.

***

<h2 id="faq">
  FAQ
</h2>

<h3 id="faq-both">
  Can I use both pandas and DataStore?
</h3>

Yes! Convert between them freely:

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

<h3 id="faq-tests">
  Will my tests still pass?
</h3>

Most tests should pass. For comparison tests, convert to pandas:

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

<h3 id="faq-jupyter">
  Can I use DataStore in Jupyter?
</h3>

Yes! DataStore works in Jupyter notebooks:

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

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

<h3 id="faq-issues">
  How do I report issues?
</h3>

If you find compatibility issues, report them at:
[https://github.com/chdb-io/chdb/issues](https://github.com/chdb-io/chdb/issues)
