> ## 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">
  ### عمليات الإدخال والإخراج
</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: DataFrame وعمليات pandas
</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 | مقدار التسريع |
| ----------------- | ------- | --------- | ------------- |
| Count في GroupBy  | 347ms   | 17ms      | **19.93x**    |
| مسار معالجة معقّد | 2,047ms | 380ms     | **5.39x**     |
| تصفية+فرز+Head    | 1,537ms | 350ms     | **4.40x**     |
| Agg في GroupBy    | 406ms   | 141ms     | **2.88x**     |

*اختبار أداء على 10 ملايين صف*

***

<div id="troubleshooting">
  ## استكشاف مشكلات الترحيل وإصلاحها
</div>

<div id="issue-op">
  ### المشكلة: العملية لا تعمل
</div>

قد لا تكون بعض عمليات pandas مدعومة. تحقّق مما يلي:

1. هل العملية مُدرجة في [قائمة التوافق](/docs/ar/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">
  ### الأسبوع الأول: اختبار التوافق
</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">
  ### الأسبوع الرابع: الترحيل الكامل
</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">
  ### هل يمكنني استخدام DataStore في Jupyter؟
</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">
  ### كيف أبلّغ عن المشكلات؟
</div>

إذا واجهت مشكلات في التوافق، فأبلِغ عنها على:
[https://github.com/chdb-io/chdb/issues](https://github.com/chdb-io/chdb/issues)
